3 +----------------------------------------------------------------------------+
4 | PayflowPro Core Payment Module for CiviCRM version 4.6 |
5 +----------------------------------------------------------------------------+
6 | Licensed to CiviCRM under the Academic Free License version 3.0 |
8 | Written & Contributed by Eileen McNaughton - 2009 |
9 +---------------------------------------------------------------------------+
13 * Class CRM_Core_Payment_PayflowPro
15 class CRM_Core_Payment_PayflowPro
extends CRM_Core_Payment
{
16 // (not used, implicit in the API, might need to convert?)
21 * We only need one instance of this object. So we use the singleton
22 * pattern and cache the instance in this variable
27 static private $_singleton = NULL;
32 * @param string $mode the mode of operation: live or test
38 * @param $paymentProcessor
40 public function __construct($mode, &$paymentProcessor) {
43 $this->_paymentProcessor
= $paymentProcessor;
44 $this->_processorName
= ts('Payflow Pro');
48 * Singleton function used to manage this object
50 * @param string $mode the mode of operation: live or test
52 * @param object $paymentProcessor
57 public static function &singleton($mode, &$paymentProcessor) {
58 $processorName = $paymentProcessor['name'];
59 if (self
::$_singleton[$processorName] === NULL) {
60 self
::$_singleton[$processorName] = new CRM_Core_Payment_PayflowPro($mode, $paymentProcessor);
62 return self
::$_singleton[$processorName];
66 * This function sends request and receives response from
67 * the processor. It is the main function for processing on-server
68 * credit card transactions
71 * This function collects all the information from a web/api form and invokes
72 * the relevant payment processor specific functions to perform the transaction
74 * @param array $params assoc array of input parameters for this transaction
76 * @return array the result in an nice formatted array (or an error object)
79 public function doDirectPayment(&$params) {
80 if (!defined('CURLOPT_SSLCERT')) {
81 CRM_Core_Error
::fatal(ts('PayFlowPro requires curl with SSL support'));
85 * define variables for connecting with the gateway
88 // Are you using the Payflow Fraud Protection Service?
89 // Default is YES, change to NO or blank if not.
90 //This has not been investigated as part of writing this payment processor
92 //if you have not set up a separate user account the vendor name is used as the username
93 if (!$this->_paymentProcessor
['subject']) {
94 $user = $this->_paymentProcessor
['user_name'];
97 $user = $this->_paymentProcessor
['subject'];
100 // ideally this id would be passed through into this class as
101 // part of the paymentProcessor
102 //object with the other variables. It seems inefficient to re-query to get it.
103 //$params['processor_id'] = CRM_Core_DAO::getFieldValue(
104 // 'CRM_Contribute_DAO_ContributionP
105 //age',$params['contributionPageID'], 'payment_processor_id' );
108 *Create the array of variables to be sent to the processor from the $params array
109 * passed into this function
113 $payflow_query_array = array(
115 'VENDOR' => $this->_paymentProcessor
['user_name'],
116 'PARTNER' => $this->_paymentProcessor
['signature'],
117 'PWD' => $this->_paymentProcessor
['password'],
118 // C - Direct Payment using credit card
120 // A - Authorization, S - Sale
122 'ACCT' => urlencode($params['credit_card_number']),
123 'CVV2' => $params['cvv2'],
124 'EXPDATE' => urlencode(sprintf('%02d', (int) $params['month']) . substr($params['year'], 2, 2)),
125 'ACCTTYPE' => urlencode($params['credit_card_type']),
126 'AMT' => urlencode($params['amount']),
127 'CURRENCY' => urlencode($params['currency']),
128 'FIRSTNAME' => $params['billing_first_name'],
130 'LASTNAME' => $params['billing_last_name'],
132 'STREET' => $params['street_address'],
133 'CITY' => urlencode($params['city']),
134 'STATE' => urlencode($params['state_province']),
135 'ZIP' => urlencode($params['postal_code']),
136 'COUNTRY' => urlencode($params['country']),
137 'EMAIL' => $params['email'],
138 'CUSTIP' => urlencode($params['ip_address']),
139 'COMMENT1' => urlencode($params['contributionType_accounting_code']),
141 'INVNUM' => urlencode($params['invoiceID']),
142 'ORDERDESC' => urlencode($params['description']),
143 'VERBOSITY' => 'MEDIUM',
144 'BILLTOCOUNTRY' => urlencode($params['country']),
147 if ($params['installments'] == 1) {
148 $params['is_recur'] == FALSE;
151 if ($params['is_recur'] == TRUE) {
153 $payflow_query_array['TRXTYPE'] = 'R';
154 $payflow_query_array['OPTIONALTRX'] = 'S';
155 $payflow_query_array['OPTIONALTRXAMT'] = $params['amount'];
156 //Amount of the initial Transaction. Required
157 $payflow_query_array['ACTION'] = 'A';
158 //A for add recurring (M-modify,C-cancel,R-reactivate,I-inquiry,P-payment
159 $payflow_query_array['PROFILENAME'] = urlencode('RegularContribution');
160 //A for add recurring (M-modify,C-cancel,R-reactivate,I-inquiry,P-payment
161 if ($params['installments'] > 0) {
162 $payflow_query_array['TERM'] = $params['installments'] - 1;
163 //ie. in addition to the one happening with this transaction
165 // $payflow_query_array['COMPANYNAME']
166 // $payflow_query_array['DESC'] = not set yet Optional
167 // description of the goods or
168 //services being purchased.
169 //This parameter applies only for ACH_CCD accounts.
171 // $payflow_query_array['MAXFAILPAYMENTS'] = 0;
172 // number of payment periods (as s
173 //pecified by PAYPERIOD) for which the transaction is allowed
174 //to fail before PayPal cancels a profile. the default
175 // value of 0 (zero) specifies no
177 //attempts occur until the term is complete.
178 // $payflow_query_array['RETRYNUMDAYS'] = (not set as can't assume business rule
180 switch ($params['frequency_unit']) {
182 $params['next_sched_contribution_date'] = mktime(0, 0, 0, date("m"), date("d") +
7,
185 $params['end_date'] = mktime(0, 0, 0, date("m"), date("d") +
(7 * $payflow_query_array['TERM']),
188 $payflow_query_array['START'] = date('mdY', $params['next_sched_contribution_date']);
189 $payflow_query_array['PAYPERIOD'] = "WEEK";
190 $params['frequency_unit'] = "week";
191 $params['frequency_interval'] = 1;
195 $params['next_sched_contribution_date'] = mktime(0, 0, 0, date("m"), date("d") +
14, date("Y"));
196 $params['end_date'] = mktime(0, 0, 0, date("m"), date("d") +
(14 * $payflow_query_array['TERM'])
199 $payflow_query_array['START'] = date('mdY', $params['next_sched_contribution_date']);
200 $payflow_query_array['PAYPERIOD'] = "BIWK";
201 $params['frequency_unit'] = "week";
202 $params['frequency_interval'] = 2;
206 $params['next_sched_contribution_date'] = mktime(0, 0, 0, date("m"), date("d") +
28, date("Y")
208 $params['end_date'] = mktime(0, 0, 0, date("m"), date("d") +
(28 * $payflow_query_array['TERM'])
211 $payflow_query_array['START'] = date('mdY', $params['next_sched_contribution_date']);
212 $payflow_query_array['PAYPERIOD'] = "FRWK";
213 $params['frequency_unit'] = "week";
214 $params['frequency_interval'] = 4;
218 $params['next_sched_contribution_date'] = mktime(0, 0, 0, date("m") +
1,
221 $params['end_date'] = mktime(0, 0, 0, date("m") +
222 (1 * $payflow_query_array['TERM']),
225 $payflow_query_array['START'] = date('mdY', $params['next_sched_contribution_date']);
226 $payflow_query_array['PAYPERIOD'] = "MONT";
227 $params['frequency_unit'] = "month";
228 $params['frequency_interval'] = 1;
232 $params['next_sched_contribution_date'] = mktime(0, 0, 0, date("m") +
3, date("d")
235 $params['end_date'] = mktime(0, 0, 0, date("m") +
236 (3 * $payflow_query_array['TERM']),
239 $payflow_query_array['START'] = date('mdY', $params['next_sched_contribution_date']);
240 $payflow_query_array['PAYPERIOD'] = "QTER";
241 $params['frequency_unit'] = "month";
242 $params['frequency_interval'] = 3;
246 $params['next_sched_contribution_date'] = mktime(0, 0, 0, date("m") +
6, date("d"),
249 $params['end_date'] = mktime(0, 0, 0, date("m") +
250 (6 * $payflow_query_array['TERM']),
253 $payflow_query_array['START'] = date('mdY', $params['next_sched_contribution_date'
256 $payflow_query_array['PAYPERIOD'] = "SMYR";
257 $params['frequency_unit'] = "month";
258 $params['frequency_interval'] = 6;
262 $params['next_sched_contribution_date'] = mktime(0, 0, 0, date("m"), date("d"),
265 $params['end_date'] = mktime(0, 0, 0, date("m"), date("d"),
267 (1 * $payflow_query_array['TEM'])
269 $payflow_query_array['START'] = date('mdY', $params['next_sched_contribution_date']);
270 $payflow_query_array['PAYPERIOD'] = "YEAR";
271 $params['frequency_unit'] = "year";
272 $params['frequency_interval'] = 1;
277 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $payflow_query_array);
278 $payflow_query = $this->convert_to_nvp($payflow_query_array);
281 * Check to see if we have a duplicate before we send
283 if ($this->_checkDupe($params['invoiceID'])) {
284 return self
::errorExit(9003, 'It appears that this transaction is a duplicate. Have you already submitted the form once? If so there may have been a connection problem. Check your email for a receipt. If you do not receive a receipt within 2 hours you can try your transaction again. If you continue to have problems please contact the site administrator.');
287 // ie. url at payment processor to submit to.
288 $submiturl = $this->_paymentProcessor
['url_site'];
290 $responseData = self
::submit_transaction($submiturl, $payflow_query);
293 * Payment successfully sent to gateway - process the response now
295 $result = strstr($responseData, "RESULT");
297 while (strlen($result)) {
299 $keypos = strpos($result, '=');
300 $keyval = substr($result, 0, $keypos);
302 $valuepos = strpos($result, '&') ?
strpos($result, '&') : strlen($result);
303 $valval = substr($result, $keypos +
1, $valuepos - $keypos - 1);
304 // decoding the respose
305 $nvpArray[$keyval] = $valval;
306 $result = substr($result, $valuepos +
1, strlen($result));
308 // get the result code to validate.
309 $result_code = $nvpArray['RESULT'];
311 echo "<p>Params array</p><br>";
314 echo "<p>Values to Payment Processor</p><br>";
315 print_r($payflow_query_array);
317 echo "<p>Results from Payment Processor</p><br>";
322 switch ($result_code) {
325 /*******************************************************
327 * This is a successful transaction. PayFlow Pro does return further information
328 * about transactions to help you identify fraud including whether they pass
329 * the cvv check, the avs check. This is stored in
330 * CiviCRM as part of the transact
331 * but not further processing is done. Business rules would need to be defined
333 *******************************************************/
334 $params['trxn_id'] = $nvpArray['PNREF'] . $nvpArray['TRXPNREF'];
335 //'trxn_id' is varchar(255) field. returned value is length 12
336 $params['trxn_result_code'] = $nvpArray['AUTHCODE'] . "-Cvv2:" . $nvpArray['CVV2MATCH'] . "-avs:" . $nvpArray['AVSADDR'];
338 if ($params['is_recur'] == TRUE) {
339 $params['recur_trxn_id'] = $nvpArray['PROFILEID'];
340 //'trxn_id' is varchar(255) field. returned value is length 12
345 return self
::errorExit(9008, "There is a payment processor configuration problem. This is usually due to invalid account information or ip restrictions on the account. You can verify ip restriction by logging // into Manager. See Service Settings >> Allowed IP Addresses. ");
348 // Hard decline from bank.
349 return self
::errorExit(9009, "Your transaction was declined ");
352 // Voice authorization required.
353 return self
::errorExit(9010, "Your Transaction is pending. Contact Customer Service to complete your order.");
356 // Issue with credit card number or expiration date.
357 return self
::errorExit(9011, "Invalid credit card information. Please re-enter.");
360 return self
::errorExit(9012, "You have not configured your payment processor with the correct credentials. Make sure you have provided both the <vendor> and the <user> variables ");
363 return self
::errorExit(9013, "Error - from payment processor: [" . $result_code . " " . $nvpArray['RESPMSG'] . "] ");
366 return self
::errorExit(9014, "Check the code - all transactions should have been headed off before they got here. Something slipped through the net");
370 * Checks to see if invoice_id already exists in db
372 * @param int $invoiceId The ID to check
374 * @return bool True if ID exists, else false
376 public function _checkDupe($invoiceId) {
377 //copied from Eway but not working and not really sure it should!
378 $contribution = new CRM_Contribute_DAO_Contribution();
379 $contribution->invoice_id
= $invoiceId;
380 return $contribution->find();
384 * Produces error message and returns from class
387 * @param null $errorCode
388 * @param null $errorMessage
392 public function &errorExit($errorCode = NULL, $errorMessage = NULL) {
393 $e = CRM_Core_Error
::singleton();
395 $e->push($errorCode, 0, NULL, $errorMessage);
398 $e->push(9000, 0, NULL, 'Unknown System Error.');
405 * NOTE: 'doTransferCheckout' not implemented
408 * @param array $params
413 public function doTransferCheckout(&$params, $component) {
414 CRM_Core_Error
::fatal(ts('This function is not implemented'));
418 * This public function checks to see if we have the right processor config values set
420 * NOTE: Called by Events and Contribute to check config params are set prior to trying
421 * register any credit card details
423 * @param string $mode the mode we are operating in (live or test) - not used
425 * returns string $errorMsg if any errors found - null if OK
429 // function checkConfig( $mode ) // CiviCRM V1.9 Declaration
431 // CiviCRM V2.0 Declaration
433 * This function checks to see if we have the right config values
435 * @internal param string $mode the mode we are operating in (live or test)
437 * @return string the error message if any
439 public function checkConfig() {
441 if (empty($this->_paymentProcessor
['user_name'])) {
442 $errorMsg[] = ' ' . ts('ssl_merchant_id is not set for this payment processor');
445 if (empty($this->_paymentProcessor
['url_site'])) {
446 $errorMsg[] = ' ' . ts('URL is not set for %1', array(1 => $this->_paymentProcessor
['name']));
449 if (!empty($errorMsg)) {
450 return implode('<p>', $errorMsg);
459 * convert to a name/value pair (nvp) string
462 * @param $payflow_query_array
464 * @return array|string
466 public function convert_to_nvp($payflow_query_array) {
467 foreach ($payflow_query_array as $key => $value) {
468 $payflow_query[] = $key . '[' . strlen($value) . ']=' . $value;
470 $payflow_query = implode('&', $payflow_query);
472 return $payflow_query;
476 * Submit transaction using CuRL
477 * @submiturl string Url to direct HTTPS GET to
478 * @payflow_query value string to be posted
483 * @param $payflow_query
485 * @return mixed|object
487 public function submit_transaction($submiturl, $payflow_query) {
489 * Submit transaction using CuRL
492 // get data ready for API
493 $user_agent = $_SERVER['HTTP_USER_AGENT'];
494 // Here's your custom headers; adjust appropriately for your setup:
495 $headers[] = "Content-Type: text/namevalue";
496 //or text/xml if using XMLPay.
497 $headers[] = "Content-Length : " . strlen($data);
498 // Length of data to be passed
499 // Here the server timeout value is set to 45, but notice
500 // below in the cURL section, the timeout
501 // for cURL is 90 seconds. You want to make sure the server
502 // timeout is less, then the connection.
503 $headers[] = "X-VPS-Timeout: 45";
504 //random unique number - the transaction is retried using this transaction ID
505 // in this function but if that doesn't work and it is re- submitted
506 // it is treated as a new attempt. PayflowPro doesn't allow
507 // you to change details (e.g. card no) when you re-submit
508 // you can only try the same details
509 $headers[] = "X-VPS-Request-ID: " . rand(1, 1000000000);
510 // optional header field
511 $headers[] = "X-VPS-VIT-Integration-Product: CiviCRM";
512 // other Optional Headers. If used adjust as necessary.
514 //$headers[] = "X-VPS-VIT-OS-Name: Linux";
516 //$headers[] = "X-VPS-VIT-OS-Version: RHEL 4";
517 // What you are using
518 //$headers[] = "X-VPS-VIT-Client-Type: PHP/cURL";
520 //$headers[] = "X-VPS-VIT-Client-Version: 0.01";
522 //$headers[] = "X-VPS-VIT-Client-Architecture: x86";
523 // Application version
524 //$headers[] = "X-VPS-VIT-Integration-Version: 0.01";
526 curl_setopt($ch, CURLOPT_URL
, $submiturl);
527 curl_setopt($ch, CURLOPT_HTTPHEADER
, $headers);
528 curl_setopt($ch, CURLOPT_USERAGENT
, $user_agent);
529 curl_setopt($ch, CURLOPT_HEADER
, 1);
530 // tells curl to include headers in response
531 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
532 // return into a variable
533 curl_setopt($ch, CURLOPT_TIMEOUT
, 90);
534 // times out after 90 secs
535 if (ini_get('open_basedir') == '' && ini_get('safe_mode') == 'Off') {
536 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, 0);
538 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
539 // this line makes it work under https
540 curl_setopt($ch, CURLOPT_POSTFIELDS
, $payflow_query);
542 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
543 //verifies ssl certificate
544 curl_setopt($ch, CURLOPT_FORBID_REUSE
, TRUE);
545 //forces closure of connection when done
546 curl_setopt($ch, CURLOPT_POST
, 1);
549 // Try to submit the transaction up to 3 times with 5 second delay. This can be used
550 // in case of network issues. The idea here is since you are posting via HTTPS there
551 // could be general network issues, so try a few times before you tell customer there
556 $responseData = curl_exec($ch);
557 $responseHeaders = curl_getinfo($ch);
558 if ($responseHeaders['http_code'] != 200) {
559 // Let's wait 5 seconds to see if its a temporary network issue.
562 elseif ($responseHeaders['http_code'] == 200) {
563 // we got a good response, drop out of loop.
569 * Transaction submitted -
570 * See if we had a curl error - if so tell 'em and bail out
572 * NOTE: curl_error does not return a logical value (see its documentation), but
573 * a string, which is empty when there was no error.
575 if ((curl_errno($ch) > 0) ||
(strlen(curl_error($ch)) > 0)) {
577 $errorNum = curl_errno($ch);
578 $errorDesc = curl_error($ch);
580 //Paranoia - in the unlikley event that 'curl' errno fails
584 // Paranoia - in the unlikley event that 'curl' error fails
585 if (strlen($errorDesc) == 0)
586 $errorDesc = "Connection to payment gateway failed";
587 if ($errorNum = 60) {
588 return self
::errorExit($errorNum, "Curl error - " . $errorDesc .
589 " Try this link for more information http://curl.haxx.se/d
594 return self
::errorExit($errorNum, "Curl error - " . $errorDesc .
595 " processor response = " . $processorResponse
600 * If null data returned - tell 'em and bail out
602 * NOTE: You will not necessarily get a string back, if the request failed for
603 * any reason, the return value will be the boolean false.
605 if (($responseData === FALSE) ||
(strlen($responseData) == 0)) {
607 return self
::errorExit(9006, "Error: Connection to payment gateway failed - no data
608 returned. Gateway url set to $submiturl");
612 * If gateway returned no data - tell 'em and bail out
614 if (empty($responseData)) {
616 return self
::errorExit(9007, "Error: No data returned from payment gateway.");
620 * Success so far - close the curl and check the data
623 return $responseData;
625 //end submit_transaction
628 * @param int $recurringProfileID
629 * @param int $processorID
633 public function getRecurringTransactionStatus($recurringProfileID, $processorID) {
634 if (!defined('CURLOPT_SSLCERT')) {
635 CRM_Core_Error
::fatal(ts('PayFlowPro requires curl with SSL support'));
639 * define variables for connecting with the gateway
642 //if you have not set up a separate user account the vendor name is used as the username
643 if (!$this->_paymentProcessor
['subject']) {
644 $user = $this->_paymentProcessor
['user_name'];
647 $user = $this->_paymentProcessor
['subject'];
649 //$recurringProfileID = "RT0000000001";
650 // c $trythis = $this->getRecurringTransactionStatus($recurringProfileID,17);
654 *Create the array of variables to be sent to the processor from the $params array
655 * passed into this function
659 $payflow_query_array = array(
661 'VENDOR' => $this->_paymentProcessor
['user_name'],
662 'PARTNER' => $this->_paymentProcessor
['signature'],
663 'PWD' => $this->_paymentProcessor
['password'],
664 // C - Direct Payment using credit card
666 // A - Authorization, S - Sale
669 //A for add recurring
670 //(M-modify,C-cancel,R-reactivate,
671 //I-inquiry,P-payment
672 'ORIGPROFILEID' => $recurringProfileID,
673 'PAYMENTHISTORY' => 'Y',
676 $payflow_query = $this->convert_to_nvp($payflow_query_array);
678 $submiturl = $this->_paymentProcessor
['url_site'];
679 //ie. url at payment processor to submit to.
680 $responseData = self
::submit_transaction($submiturl, $payflow_query);
682 * Payment successfully sent to gateway - process the response now
685 $result = strstr($responseData, "RESULT");
687 while (strlen($result)) {
689 $keypos = strpos($result, '=');
690 $keyval = substr($result, 0, $keypos);
692 $valuepos = strpos($result, '&') ?
strpos($result, '&') : strlen($result);
693 $valval = substr($result, $keypos +
1, $valuepos - $keypos - 1);
694 // decoding the respose
695 $nvpArray[$keyval] = $valval;
696 $result = substr($result, $valuepos +
1, strlen($result));
698 // get the result code to validate.
699 $result_code = $nvpArray['RESULT'];
700 print_r($responseData);
702 //RESPMSG=Invalid Profile ID: Invalid recurring profile ID