| 1 | <?php |
| 2 | /* |
| 3 | * Copyright (C) 2012 |
| 4 | * Licensed to CiviCRM under the GPL v3 or higher |
| 5 | * |
| 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) |
| 8 | * |
| 9 | */ |
| 10 | |
| 11 | // Define logging level (0 = off, 4 = log everything) |
| 12 | define('TRUSTCOMMERCE_LOGGING_LEVEL', 4); |
| 13 | |
| 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'; |
| 21 | |
| 22 | static protected $_mode = NULL; |
| 23 | |
| 24 | static protected $_params = array(); |
| 25 | |
| 26 | /** |
| 27 | * We only need one instance of this object. So we use the singleton |
| 28 | * pattern and cache the instance in this variable |
| 29 | * |
| 30 | * @var object |
| 31 | * @static |
| 32 | */ |
| 33 | static private $_singleton = NULL; |
| 34 | |
| 35 | /** |
| 36 | * Constructor |
| 37 | * |
| 38 | * @param string $mode the mode of operation: live or test |
| 39 | * |
| 40 | * @return void |
| 41 | */ function __construct($mode, &$paymentProcessor) { |
| 42 | $this->_mode = $mode; |
| 43 | |
| 44 | $this->_paymentProcessor = $paymentProcessor; |
| 45 | |
| 46 | $this->_processorName = ts('TrustCommerce'); |
| 47 | |
| 48 | $config = CRM_Core_Config::singleton(); |
| 49 | $this->_setParam('user_name', $paymentProcessor['user_name']); |
| 50 | $this->_setParam('password', $paymentProcessor['password']); |
| 51 | |
| 52 | $this->_setParam('timestamp', time()); |
| 53 | srand(time()); |
| 54 | $this->_setParam('sequence', rand(1, 1000)); |
| 55 | $this->logging_level = TRUSTCOMMERCE_LOGGING_LEVEL; |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * singleton function used to manage this object |
| 60 | * |
| 61 | * @param string $mode the mode of operation: live or test |
| 62 | * |
| 63 | * @return object |
| 64 | * @static |
| 65 | * |
| 66 | */ |
| 67 | static |
| 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); |
| 72 | } |
| 73 | return self::$_singleton[$processorName]; |
| 74 | } |
| 75 | |
| 76 | /** |
| 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. |
| 80 | * @public |
| 81 | */ |
| 82 | function doDirectPayment(&$params) { |
| 83 | if (!extension_loaded("tclink")) { |
| 84 | return self::error(9001, 'TrustCommerce requires that the tclink module is loaded'); |
| 85 | } |
| 86 | |
| 87 | /* Copy our paramaters to ourself */ |
| 88 | foreach ($params as $field => $value) { |
| 89 | $this->_setParam($field, $value); |
| 90 | } |
| 91 | |
| 92 | /* Get our fields to pass to tclink_send() */ |
| 93 | $tc_params = $this->_getTrustCommerceFields(); |
| 94 | |
| 95 | /* Are we recurring? If so add the extra API fields. */ |
| 96 | if (CRM_Utils_Array::value('is_recur', $params) && $params['contributionRecurID']) { |
| 97 | $tc_params = $this->_getRecurPaymentFields($tc_params); |
| 98 | } |
| 99 | |
| 100 | /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */ |
| 101 | CRM_Utils_Hook::alterPaymentProcessorParams($this, |
| 102 | $params, |
| 103 | $tc_params |
| 104 | ); |
| 105 | |
| 106 | // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction |
| 107 | if ($this->_checkDupe($tc_params['ticket'])) { |
| 108 | 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.'); |
| 109 | } |
| 110 | |
| 111 | /* Call the TC API, and grab the reply */ |
| 112 | $reply = tclink_send($tc_params); |
| 113 | |
| 114 | /* Parse our reply */ |
| 115 | $result = $this->_getTrustCommerceReply($reply); |
| 116 | |
| 117 | if($result == 0) { |
| 118 | /* We were successful, congrats. Lets wrap it up: |
| 119 | * Convert back to dollars |
| 120 | * Save the transaction ID |
| 121 | */ |
| 122 | $params['trxn_id'] = $reply['transid']; |
| 123 | $params['gross_amount'] = $tc_params['amount'] / 100; |
| 124 | |
| 125 | return $params; |
| 126 | |
| 127 | } else { |
| 128 | /* Otherwise we return the error object */ |
| 129 | return $result; |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * Gets the recurring billing fields for the TC API |
| 135 | * @param array $fields The fields to modify. |
| 136 | * @return array The fields for tclink_send(), modified for recurring billing. |
| 137 | * @public |
| 138 | */ |
| 139 | function _getRecurPaymentFields($fields) { |
| 140 | $payments = $this->_getParam('frequency_interval'); |
| 141 | $cycle = $this->_getParam('frequency_unit'); |
| 142 | |
| 143 | /* Translate billing cycle from CiviCRM -> TC */ |
| 144 | switch($cycle) { |
| 145 | case 'day': |
| 146 | $cycle = 'd'; |
| 147 | break; |
| 148 | case 'week': |
| 149 | $cycle = 'w'; |
| 150 | break; |
| 151 | case 'month': |
| 152 | $cycle = 'm'; |
| 153 | break; |
| 154 | case 'year': |
| 155 | $cycle = 'y'; |
| 156 | break; |
| 157 | default: |
| 158 | return self::error(9001, 'Payment interval not set! Unable to process payment.'); |
| 159 | break; |
| 160 | } |
| 161 | |
| 162 | |
| 163 | $params['authnow'] = 'y'; /* Process this payment `now' */ |
| 164 | $params['cycle'] = $cycle; /* The billing cycle in years, months, weeks, or days. */ |
| 165 | $params['payments'] = $payments; |
| 166 | |
| 167 | |
| 168 | $tclink = $this->_getTrustCommerceFields(); |
| 169 | |
| 170 | // Set up our call for hook_civicrm_paymentProcessor, |
| 171 | // since we now have our parameters as assigned for the AIM back end. |
| 172 | CRM_Utils_Hook::alterPaymentProcessorParams($this, |
| 173 | $params, |
| 174 | $tclink |
| 175 | ); |
| 176 | |
| 177 | // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction |
| 178 | if ($this->_checkDupe($tclink['ticket'])) { |
| 179 | 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.'); |
| 180 | } |
| 181 | |
| 182 | $result = tclink_send($tclink); |
| 183 | |
| 184 | $result = _getTrustCommereceResponse($result); |
| 185 | |
| 186 | if($result == 0) { |
| 187 | /* Transaction was sucessful */ |
| 188 | $params['trxn_id'] = $result['transid']; /* Get our transaction ID */ |
| 189 | $params['gross_amount'] = $tclink['amount']/100; /* Convert from cents to dollars */ |
| 190 | return $params; |
| 191 | } else { |
| 192 | /* Transaction was *not* successful */ |
| 193 | return $result; |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | /* Parses a response from TC via the tclink_send() command. |
| 198 | * @param $reply array The result of a call to tclink_send(). |
| 199 | * @return mixed self::error() if transaction failed, otherwise returns 0. |
| 200 | */ |
| 201 | function _getTrustCommerceResponse($reply) { |
| 202 | |
| 203 | /* DUPLIATE CODE, please refactor. ~lisa */ |
| 204 | if (!$result) { |
| 205 | return self::error(9002, 'Could not initiate connection to payment gateway'); |
| 206 | } |
| 207 | |
| 208 | switch($result['status']) { |
| 209 | case self::AUTH_APPROVED: |
| 210 | // It's all good |
| 211 | break; |
| 212 | case self::AUTH_DECLINED: |
| 213 | // TODO FIXME be more or less specific? |
| 214 | // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity |
| 215 | // See TC documentation for more info |
| 216 | return self::error(9009, "Your transaction was declined: {$result['declinetype']}"); |
| 217 | break; |
| 218 | case self::AUTH_BADDATA: |
| 219 | // TODO FIXME do something with $result['error'] and $result['offender'] |
| 220 | return self::error(9011, "Invalid credit card information. Please re-enter."); |
| 221 | break; |
| 222 | case self::AUTH_ERROR: |
| 223 | return self::error(9002, 'Could not initiate connection to payment gateway'); |
| 224 | break; |
| 225 | } |
| 226 | return 0; |
| 227 | } |
| 228 | |
| 229 | function _getTrustCommerceFields() { |
| 230 | // Total amount is from the form contribution field |
| 231 | $amount = $this->_getParam('total_amount'); |
| 232 | // CRM-9894 would this ever be the case?? |
| 233 | if (empty($amount)) { |
| 234 | $amount = $this->_getParam('amount'); |
| 235 | } |
| 236 | $fields = array(); |
| 237 | $fields['custid'] = $this->_getParam('user_name'); |
| 238 | $fields['password'] = $this->_getParam('password'); |
| 239 | $fields['action'] = 'sale'; |
| 240 | |
| 241 | // Enable address verification |
| 242 | $fields['avs'] = 'y'; |
| 243 | |
| 244 | $fields['address1'] = $this->_getParam('street_address'); |
| 245 | $fields['zip'] = $this->_getParam('postal_code'); |
| 246 | |
| 247 | $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name'); |
| 248 | |
| 249 | // This assumes currencies where the . is used as the decimal point, like USD |
| 250 | $amount = preg_replace("/([^0-9\\.])/i", "", $amount); |
| 251 | |
| 252 | // We need to pass the amount to TrustCommerce in dollar cents |
| 253 | $fields['amount'] = $amount * 100; |
| 254 | |
| 255 | // Unique identifier |
| 256 | $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20); |
| 257 | |
| 258 | // cc info |
| 259 | $fields['cc'] = $this->_getParam('credit_card_number'); |
| 260 | $fields['cvv'] = $this->_getParam('cvv2'); |
| 261 | $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT); |
| 262 | $exp_year = substr($this->_getParam('year'),-2); |
| 263 | $fields['exp'] = "$exp_month$exp_year"; |
| 264 | |
| 265 | if ($this->_mode != 'live') { |
| 266 | $fields['demo'] = 'y'; |
| 267 | } |
| 268 | return $fields; |
| 269 | } |
| 270 | |
| 271 | /** |
| 272 | * Checks to see if invoice_id already exists in db |
| 273 | * |
| 274 | * @param int $invoiceId The ID to check |
| 275 | * |
| 276 | * @return bool True if ID exists, else false |
| 277 | */ |
| 278 | function _checkDupe($invoiceId) { |
| 279 | require_once 'CRM/Contribute/DAO/Contribution.php'; |
| 280 | $contribution = new CRM_Contribute_DAO_Contribution(); |
| 281 | $contribution->invoice_id = $invoiceId; |
| 282 | return $contribution->find(); |
| 283 | } |
| 284 | |
| 285 | /** |
| 286 | * Get the value of a field if set |
| 287 | * |
| 288 | * @param string $field the field |
| 289 | * |
| 290 | * @return mixed value of the field, or empty string if the field is |
| 291 | * not set |
| 292 | */ |
| 293 | function _getParam($field) { |
| 294 | return CRM_Utils_Array::value($field, $this->_params, ''); |
| 295 | } |
| 296 | |
| 297 | function &error($errorCode = NULL, $errorMessage = NULL) { |
| 298 | $e = CRM_Core_Error::singleton(); |
| 299 | if ($errorCode) { |
| 300 | $e->push($errorCode, 0, NULL, $errorMessage); |
| 301 | } |
| 302 | else { |
| 303 | $e->push(9001, 0, NULL, 'Unknown System Error.'); |
| 304 | } |
| 305 | return $e; |
| 306 | } |
| 307 | |
| 308 | /** |
| 309 | * Set a field to the specified value. Value must be a scalar (int, |
| 310 | * float, string, or boolean) |
| 311 | * |
| 312 | * @param string $field |
| 313 | * @param mixed $value |
| 314 | * |
| 315 | * @return bool false if value is not a scalar, true if successful |
| 316 | */ |
| 317 | function _setParam($field, $value) { |
| 318 | if (!is_scalar($value)) { |
| 319 | return FALSE; |
| 320 | } |
| 321 | else { |
| 322 | $this->_params[$field] = $value; |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | /** |
| 327 | * This function checks to see if we have the right config values |
| 328 | * |
| 329 | * @return string the error message if any |
| 330 | * @public |
| 331 | */ |
| 332 | function checkConfig() { |
| 333 | $error = array(); |
| 334 | if (empty($this->_paymentProcessor['user_name'])) { |
| 335 | $error[] = ts('Customer ID is not set for this payment processor'); |
| 336 | } |
| 337 | |
| 338 | if (empty($this->_paymentProcessor['password'])) { |
| 339 | $error[] = ts('Password is not set for this payment processor'); |
| 340 | } |
| 341 | |
| 342 | if (!empty($error)) { |
| 343 | return implode('<p>', $error); |
| 344 | } else { |
| 345 | return NULL; |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | function cancelSubscriptionURL($entityID = NULL, $entity = NULL) { |
| 350 | if ($entityID && $entity == 'membership') { |
| 351 | require_once 'CRM/Contact/BAO/Contact/Utils.php'; |
| 352 | $contactID = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id"); |
| 353 | $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf'); |
| 354 | |
| 355 | return CRM_Utils_System::url('civicrm/contribute/unsubscribe', |
| 356 | "reset=1&mid={$entityID}&cs={$checksumValue}", TRUE, NULL, FALSE, FALSE |
| 357 | ); |
| 358 | } |
| 359 | |
| 360 | return ($this->_mode == 'test') ? 'https://test.authorize.net' : 'https://authorize.net'; |
| 361 | } |
| 362 | |
| 363 | function cancelSubscription() { |
| 364 | $template = CRM_Core_Smarty::singleton(); |
| 365 | |
| 366 | $template->assign('subscriptionType', 'cancel'); |
| 367 | |
| 368 | $template->assign('apiLogin', $this->_getParam('apiLogin')); |
| 369 | $template->assign('paymentKey', $this->_getParam('paymentKey')); |
| 370 | $template->assign('subscriptionId', $this->_getParam('subscriptionId')); |
| 371 | |
| 372 | $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl'); |
| 373 | |
| 374 | // submit to authorize.net |
| 375 | $submit = curl_init($this->_paymentProcessor['url_recur']); |
| 376 | if (!$submit) { |
| 377 | return self::error(9002, 'Could not initiate connection to payment gateway'); |
| 378 | } |
| 379 | |
| 380 | curl_setopt($submit, CURLOPT_RETURNTRANSFER, 1); |
| 381 | curl_setopt($submit, CURLOPT_HTTPHEADER, array("Content-Type: text/xml")); |
| 382 | curl_setopt($submit, CURLOPT_HEADER, 1); |
| 383 | curl_setopt($submit, CURLOPT_POSTFIELDS, $arbXML); |
| 384 | curl_setopt($submit, CURLOPT_POST, 1); |
| 385 | curl_setopt($submit, CURLOPT_SSL_VERIFYPEER, 0); |
| 386 | |
| 387 | $response = curl_exec($submit); |
| 388 | |
| 389 | if (!$response) { |
| 390 | return self::error(curl_errno($submit), curl_error($submit)); |
| 391 | } |
| 392 | |
| 393 | curl_close($submit); |
| 394 | |
| 395 | $responseFields = $this->_ParseArbReturn($response); |
| 396 | |
| 397 | if ($responseFields['resultCode'] == 'Error') { |
| 398 | return self::error($responseFields['code'], $responseFields['text']); |
| 399 | } |
| 400 | |
| 401 | // carry on cancelation procedure |
| 402 | return TRUE; |
| 403 | } |
| 404 | |
| 405 | public function install() { |
| 406 | return TRUE; |
| 407 | } |
| 408 | |
| 409 | public function uninstall() { |
| 410 | return TRUE; |
| 411 | } |
| 412 | |
| 413 | } |