4 * Licensed to CiviCRM under the GPL v3 or higher
6 * Written and contributed by Ward Vandewege <ward@fsf.org> (http://www.fsf.org)
10 // Define logging level (0 = off, 4 = log everything)
11 define('TRUSTCOMMERCE_LOGGING_LEVEL', 4);
13 require_once 'CRM/Core/Payment.php';
14 class org_fsf_payment_trustcommerce
extends CRM_Core_Payment
{
15 CONST CHARSET
= 'iso-8859-1';
16 CONST AUTH_APPROVED
= 'approve';
17 CONST AUTH_DECLINED
= 'decline';
18 CONST AUTH_BADDATA
= 'baddata';
19 CONST AUTH_ERROR
= 'error';
21 static protected $_mode = NULL;
23 static protected $_params = array();
26 * We only need one instance of this object. So we use the singleton
27 * pattern and cache the instance in this variable
32 static private $_singleton = NULL;
37 * @param string $mode the mode of operation: live or test
40 */ function __construct($mode, &$paymentProcessor) {
43 $this->_paymentProcessor
= $paymentProcessor;
45 $this->_processorName
= ts('TrustCommerce');
47 $config = CRM_Core_Config
::singleton();
48 $this->_setParam('user_name', $paymentProcessor['user_name']);
49 $this->_setParam('password', $paymentProcessor['password']);
51 $this->_setParam('timestamp', time());
53 $this->_setParam('sequence', rand(1, 1000));
54 $this->logging_level
= TRUSTCOMMERCE_LOGGING_LEVEL
;
58 * singleton function used to manage this object
60 * @param string $mode the mode of operation: live or test
67 function &singleton($mode, &$paymentProcessor) {
68 $processorName = $paymentProcessor['name'];
69 if (self
::$_singleton[$processorName] === NULL) {
70 self
::$_singleton[$processorName] = new org_fsf_payment_trustcommerce($mode, $paymentProcessor);
72 return self
::$_singleton[$processorName];
76 * Submit a payment using Advanced Integration Method
78 * @param array $params assoc array of input parameters for this transaction
80 * @return array the result in a nice formatted array (or an error object)
83 function doDirectPayment(&$params) {
84 if (!extension_loaded("tclink")) {
85 return self
::error(9001, 'TrustCommerce requires that the tclink module is loaded');
89 * recurpayment function does not compile an array & then proces it -
90 * - the tpl does the transformation so adding call to hook here
91 * & giving it a change to act on the params array
95 if (CRM_Utils_Array
::value('is_recur', $params) &&
96 $params['contributionRecurID']
98 CRM_Utils_Hook
::alterPaymentProcessorParams($this,
103 foreach ($newParams as $field => $value) {
104 $this->_setParam($field, $value);
107 if (CRM_Utils_Array
::value('is_recur', $params) &&
108 $params['contributionRecurID']
110 return $this->doRecurPayment($params);
113 $postFields = array();
114 $tclink = $this->_getTrustCommerceFields();
116 // Set up our call for hook_civicrm_paymentProcessor,
117 // since we now have our parameters as assigned for the AIM back end.
118 CRM_Utils_Hook
::alterPaymentProcessorParams($this,
123 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
124 if ($this->_checkDupe($tclink['ticket'])) {
125 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.');
128 $result = tclink_send($tclink);
131 return self
::error(9002, 'Could not initiate connection to payment gateway');
134 foreach ($result as $field => $value) {
135 error_log("result: $field => $value");
138 switch($result['status']) {
139 case self
::AUTH_APPROVED
:
142 case self
::AUTH_DECLINED
:
143 // TODO FIXME be more or less specific?
144 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
145 // See TC documentation for more info
146 return self
::error(9009, "Your transaction was declined: {$result['declinetype']}");
148 case self
::AUTH_BADDATA
:
149 // TODO FIXME do something with $result['error'] and $result['offender']
150 return self
::error(9011, "Invalid credit card information. Please re-enter.");
152 case self
::AUTH_ERROR
:
153 return self
::error(9002, 'Could not initiate connection to payment gateway');
159 $params['trxn_id'] = $result['transid'];
160 $params['gross_amount'] = $tclink['amount'] / 100;
166 * Submit an Automated Recurring Billing subscription
168 * @param array $params assoc array of input parameters for this transaction
170 * @return array the result in a nice formatted array (or an error object)
173 function doRecurPayment(&$params) {
174 $template = CRM_Core_Smarty
::singleton();
176 $intervalLength = $this->_getParam('frequency_interval');
177 $intervalUnit = $this->_getParam('frequency_unit');
178 if ($intervalUnit == 'week') {
179 $intervalLength *= 7;
180 $intervalUnit = 'days';
182 elseif ($intervalUnit == 'year') {
183 $intervalLength *= 12;
184 $intervalUnit = 'months';
186 elseif ($intervalUnit == 'day') {
187 $intervalUnit = 'days';
189 elseif ($intervalUnit == 'month') {
190 $intervalUnit = 'months';
193 // interval cannot be less than 7 days or more than 1 year
194 if ($intervalUnit == 'days') {
195 if ($intervalLength < 7) {
196 return self
::error(9001, 'Payment interval must be at least one week');
198 elseif ($intervalLength > 365) {
199 return self
::error(9001, 'Payment interval may not be longer than one year');
202 elseif ($intervalUnit == 'months') {
203 if ($intervalLength < 1) {
204 return self
::error(9001, 'Payment interval must be at least one week');
206 elseif ($intervalLength > 12) {
207 return self
::error(9001, 'Payment interval may not be longer than one year');
211 $template->assign('intervalLength', $intervalLength);
212 $template->assign('intervalUnit', $intervalUnit);
214 $template->assign('apiLogin', $this->_getParam('apiLogin'));
215 $template->assign('paymentKey', $this->_getParam('paymentKey'));
216 $template->assign('refId', substr($this->_getParam('invoiceID'), 0, 20));
218 //for recurring, carry first contribution id
219 $template->assign('invoiceNumber', $this->_getParam('contributionID'));
220 $firstPaymentDate = $this->_getParam('receive_date');
221 if (!empty($firstPaymentDate)) {
222 //allow for post dated payment if set in form
223 $template->assign('startDate', date('Y-m-d', strtotime($firstPaymentDate)));
226 $template->assign('startDate', date('Y-m-d'));
228 // for open ended subscription totalOccurrences has to be 9999
229 $installments = $this->_getParam('installments');
230 $template->assign('totalOccurrences', $installments ?
$installments : 9999);
232 $template->assign('amount', $this->_getParam('amount'));
234 $template->assign('cardNumber', $this->_getParam('credit_card_number'));
235 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT
);
236 $exp_year = $this->_getParam('year');
237 $template->assign('expirationDate', $exp_year . '-' . $exp_month);
238 // name rather than description is used in the tpl - see http://www.authorize.net/support/ARB_guide.pdf
239 $template->assign('name', $this->_getParam('description'));
241 $template->assign('email', $this->_getParam('email'));
242 $template->assign('contactID', $this->_getParam('contactID'));
243 $template->assign('billingFirstName', $this->_getParam('billing_first_name'));
244 $template->assign('billingLastName', $this->_getParam('billing_last_name'));
245 $template->assign('billingAddress', $this->_getParam('street_address'));
246 $template->assign('billingCity', $this->_getParam('city'));
247 $template->assign('billingState', $this->_getParam('state_province'));
248 $template->assign('billingZip', $this->_getParam('postal_code'));
249 $template->assign('billingCountry', $this->_getParam('country'));
251 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
252 // submit to authorize.net
254 $submit = curl_init($this->_paymentProcessor
['url_recur']);
256 return self
::error(9002, 'Could not initiate connection to payment gateway');
258 curl_setopt($submit, CURLOPT_RETURNTRANSFER
, 1);
259 curl_setopt($submit, CURLOPT_HTTPHEADER
, array("Content-Type: text/xml"));
260 curl_setopt($submit, CURLOPT_HEADER
, 1);
261 curl_setopt($submit, CURLOPT_POSTFIELDS
, $arbXML);
262 curl_setopt($submit, CURLOPT_POST
, 1);
263 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER
, 0);
265 $response = curl_exec($submit);
268 return self
::error(curl_errno($submit), curl_error($submit));
272 $responseFields = $this->_ParseArbReturn($response);
274 if ($responseFields['resultCode'] == 'Error') {
275 return self
::error($responseFields['code'], $responseFields['text']);
278 // update recur processor_id with subscriptionId
279 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_ContributionRecur', $params['contributionRecurID'],
280 'processor_id', $responseFields['subscriptionId']
282 //only impact of assigning this here is is can be used to cancel the subscription in an automated test
283 // if it isn't cancelled a duplicate transaction error occurs
284 if (CRM_Utils_Array
::value('subscriptionId', $responseFields)) {
285 $this->_setParam('subscriptionId', $responseFields['subscriptionId']);
290 function _getTrustCommerceFields() {
291 // Total amount is from the form contribution field
292 $amount = $this->_getParam('total_amount');
293 // CRM-9894 would this ever be the case??
294 if (empty($amount)) {
295 $amount = $this->_getParam('amount');
298 $fields['custid'] = $this->_getParam('user_name');
299 $fields['password'] = $this->_getParam('password');
300 $fields['action'] = 'sale';
302 // Enable address verification
303 $fields['avs'] = 'y';
305 $fields['address1'] = $this->_getParam('street_address');
306 $fields['zip'] = $this->_getParam('postal_code');
308 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
310 // This assumes currencies where the . is used as the decimal point, like USD
311 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
313 // We need to pass the amount to TrustCommerce in dollar cents
314 $fields['amount'] = $amount * 100;
317 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
320 $fields['cc'] = $this->_getParam('credit_card_number');
321 $fields['cvv'] = $this->_getParam('cvv2');
322 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT
);
323 $exp_year = substr($this->_getParam('year'),-2);
324 $fields['exp'] = "$exp_month$exp_year";
326 if ($this->_mode
!= 'live') {
327 $fields['demo'] = 'y';
330 foreach ($fields as $field => $value) {
331 if ($field == 'custid') $value = '********';
332 if ($field == 'password') $value = '********';
333 if ($field == 'cc') $value = '********';
334 if ($field == 'cvv') $value = '********';
335 if ($field == 'exp') $value = '********';
336 error_log("fields: $field => $value");
343 * Checks to see if invoice_id already exists in db
345 * @param int $invoiceId The ID to check
347 * @return bool True if ID exists, else false
349 function _checkDupe($invoiceId) {
350 require_once 'CRM/Contribute/DAO/Contribution.php';
351 $contribution = new CRM_Contribute_DAO_Contribution();
352 $contribution->invoice_id
= $invoiceId;
353 return $contribution->find();
357 * Get the value of a field if set
359 * @param string $field the field
361 * @return mixed value of the field, or empty string if the field is
364 function _getParam($field) {
365 return CRM_Utils_Array
::value($field, $this->_params
, '');
368 function &error($errorCode = NULL, $errorMessage = NULL) {
369 $e = CRM_Core_Error
::singleton();
371 $e->push($errorCode, 0, NULL, $errorMessage);
374 $e->push(9001, 0, NULL, 'Unknown System Error.');
380 * Set a field to the specified value. Value must be a scalar (int,
381 * float, string, or boolean)
383 * @param string $field
384 * @param mixed $value
386 * @return bool false if value is not a scalar, true if successful
388 function _setParam($field, $value) {
389 if (!is_scalar($value)) {
393 $this->_params
[$field] = $value;
398 * This function checks to see if we have the right config values
400 * @return string the error message if any
403 function checkConfig() {
405 if (empty($this->_paymentProcessor
['user_name'])) {
406 $error[] = ts('Customer ID is not set for this payment processor');
409 if (empty($this->_paymentProcessor
['password'])) {
410 $error[] = ts('Password is not set for this payment processor');
413 if (!empty($error)) {
414 return implode('<p>', $error);
420 function cancelSubscriptionURL($entityID = NULL, $entity = NULL) {
421 if ($entityID && $entity == 'membership') {
422 require_once 'CRM/Contact/BAO/Contact/Utils.php';
423 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
424 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
426 return CRM_Utils_System
::url('civicrm/contribute/unsubscribe',
427 "reset=1&mid={$entityID}&cs={$checksumValue}", TRUE, NULL, FALSE, FALSE
431 return ($this->_mode
== 'test') ?
'https://test.authorize.net' : 'https://authorize.net';
434 function cancelSubscription() {
435 $template = CRM_Core_Smarty
::singleton();
437 $template->assign('subscriptionType', 'cancel');
439 $template->assign('apiLogin', $this->_getParam('apiLogin'));
440 $template->assign('paymentKey', $this->_getParam('paymentKey'));
441 $template->assign('subscriptionId', $this->_getParam('subscriptionId'));
443 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
445 // submit to authorize.net
446 $submit = curl_init($this->_paymentProcessor
['url_recur']);
448 return self
::error(9002, 'Could not initiate connection to payment gateway');
451 curl_setopt($submit, CURLOPT_RETURNTRANSFER
, 1);
452 curl_setopt($submit, CURLOPT_HTTPHEADER
, array("Content-Type: text/xml"));
453 curl_setopt($submit, CURLOPT_HEADER
, 1);
454 curl_setopt($submit, CURLOPT_POSTFIELDS
, $arbXML);
455 curl_setopt($submit, CURLOPT_POST
, 1);
456 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER
, 0);
458 $response = curl_exec($submit);
461 return self
::error(curl_errno($submit), curl_error($submit));
466 $responseFields = $this->_ParseArbReturn($response);
468 if ($responseFields['resultCode'] == 'Error') {
469 return self
::error($responseFields['code'], $responseFields['text']);
472 // carry on cancelation procedure
476 public function install() {
480 public function uninstall() {