Commit e72579d7 authored by jenlampton's avatar jenlampton

Refactor responce handling into separate function.

parent 3c238e3c
......@@ -239,160 +239,50 @@ function authorizenetwebform_webform_client_form_submit($form, &$form_state) {
// @todo Fix hard-coded specific webform options.
switch ($field_values[$type_key]) {
case 'one-time':
$transaction_type = 'createTransactionRequest';
$transaction_types = array(
'createTransactionRequest',
);
break;
case 'subscription':
$transaction_type = 'ARBCreateSubscriptionRequest';
// Do one one-time transaction, followed by a recurring transaction.
$transaction_types = array(
//'createTransactionRequest',
'ARBCreateSubscriptionRequest'
);
break;
}
// Prepre data to send to AuthNet, and encode as JSON.
$data = _authorizenetwebform_prepare_data($transaction_type, $nid, $field_values);
$json = json_encode($data);
foreach ($transaction_types as $transaction_type) {
// Prepre data to send to AuthNet, and encode as JSON.
$data = _authorizenetwebform_prepare_data($transaction_type, $nid, $field_values);
$json = json_encode($data);
// Set the post URL.
$post_url = 'https://api.authorize.net/xml/v1/request.api';
if (variable_get('authorizenetwebform_mode', 'main') == 'test') {
$post_url = 'https://apitest.authorize.net/xml/v1/request.api';
}
$request = curl_init($post_url); // initiate curl object
curl_setopt($request, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
curl_setopt($request, CURLOPT_POSTFIELDS, $json); // use HTTP POST to send form data
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
$post_response = curl_exec($request); // execute curl post and store results in $post_response
@curl_close ($request); // close curl object
// Fix brokenness in the AuthNet JSON API response -- START.
$tmp_bom = pack('H*','EFBBBF');
$post_response = preg_replace("/^$tmp_bom/", '', $post_response);
unset($tmp_bom);
// Fix brokenness in the AuthNet JSON API response -- END.
$response_array = json_decode(trim($post_response), TRUE);
if ($response_array['messages']['resultCode'] == 'Ok') {
$text = '';
$failure = FALSE;
$response_info = array();
// Extrat the response info we need for our records.
if (isset($response_array['transactionResponse'])) {
$response_info = $response_array['transactionResponse'];
}
// Decliend || Error.
if (!empty($response_info) && isset($response_info['responseCode']) &&
($response_info['responseCode'] == 2 || $response_info['responseCode'] == 3)) {
$failure = TRUE;
}
else {
// Add subscription info.
if (array_key_exists('subscriptionId', $response_array)) {
$id = $response_array['subscriptionId'];
$text .= ' ' . t('Your subscription ID is @id', array('@id' => $id));
}
// Success! Set the message.
drupal_set_message('Thank you. Your payment has been processed.');
}
// Failure :( Set the form error.
if ($failure) {
if (!empty($response_info) && !empty($response_info['errors'])) {
foreach ($response_info['errors'] as $info) {
$code = $info['errorCode'];
$text = $info['errorText'];
// Log to watchdog.
$variables = array('@code' => $code, '@message' => $text);
watchdog('authorizenetwebform', 'transactionResponse error @code from Authorize.net: @message',
$variables, WATCHDOG_ERROR);
// Print to screen.
$string = $text . ' (Error code: ' . $code . ')';
drupal_set_message($string, 'error');
form_set_error(NULL, $string);
// Stop the submission.
$form_state['rebuild'] = TRUE;
}
}
form_set_error(NULL, $text);
// Stop the submission.
$form_state['rebuild'] = TRUE;
}
$response_code_options = array(
'1' => 'Approved',
'2' => 'Declined',
'3' => 'Error',
'4' => 'Held for Review',
);
$response_code = $response_code_options[$response_info['responseCode']];
$response_id = $response_info['transId'];
$response_hash = $response_info['transHash'];
$response_cc_safe = $response_info['accountNumber'];
// Get Transaction ID Component ID: webform field => component ID.
$node = node_load($nid);
$webform_field_name = $flipped_map['x_trans_id'];
$component_ids = _authorizenetwebform_get_component_ids($node);
$trans_cid = $component_ids[$webform_field_name];
// Update the webform submission Transaction ID.
$form_state['values']['submitted'][$trans_cid] = $response_id;
// Always log some response data to watchdog.
$message = 'Transaction !code. Transaction ID: !id. Transaction Hash: !hash. Credit card: !cc';
$variables = array(
'!code' => $response_code,
'!id' => $response_id,
'!hash' => $response_hash,
'!cc' => $response_cc_safe,
);
watchdog('authorizenetwebform', $message, $variables, WATCHDOG_NOTICE);
// Record the entire response if debug mode is on.
if (variable_get('authorizenetwebform_debug', FALSE)) {
// @todo: Save this data into a more permanent location than watchdog?
$message = 'The data set sent to Auth.Net follows:<br/> !string';
$string = '<pre>' . print_r($data, TRUE) . '</pre>';
$variables = array('!string' => $string);
watchdog('authorizenetwebform', $message, $variables, WATCHDOG_INFO);
$message = 'The complete response string from Auth.Net follows:<br/> !string';
$string = '<pre>' . print_r($response_array, TRUE) . '</pre>';
$variables = array('!string' => $string);
watchdog('authorizenetwebform', $message, $variables, WATCHDOG_INFO);
// Also print response to screen if devel is enabled.
if (module_exists('devel')) {
dpm($response_array);
}
// Set the post URL.
$post_url = 'https://api.authorize.net/xml/v1/request.api';
if (variable_get('authorizenetwebform_mode', 'main') == 'test') {
$post_url = 'https://apitest.authorize.net/xml/v1/request.api';
}
}
elseif ($response_array['messages']['resultCode'] == 'Error') {
foreach ($response_array['messages']['message'] as $info) {
$code = $info['code'];
$text = $info['text'];
// Send the data.
$request = curl_init($post_url); // initiate curl object
curl_setopt($request, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
curl_setopt($request, CURLOPT_POSTFIELDS, $json); // use HTTP POST to send form data
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
$post_response = curl_exec($request); // execute curl post and store results in $post_response
@curl_close ($request); // close curl object
// Log to watchdog.
$variables = array('@code' => $code, '@message' => $text);
watchdog('authorizenetwebform', 'Error @code from Authorize.net: @message',
$variables, WATCHDOG_ERROR);
// Fix brokenness in the AuthNet JSON API response -- START.
$tmp_bom = pack('H*','EFBBBF');
$post_response = preg_replace("/^$tmp_bom/", '', $post_response);
unset($tmp_bom);
// Fix brokenness in the AuthNet JSON API response -- END.
// Print to screen.
drupal_set_message($code . ': ' . $text, 'error');
form_set_error(NULL, $code . ': ' . $text);
// Decode the response.
$response_array = json_decode(trim($post_response), TRUE);
// Stop the submission.
$form_state['rebuild'] = TRUE;
}
// Handle the result.
_authorizenetwebform_handle_result($response_array, $nid, $data);
}
}
......@@ -764,92 +654,100 @@ function _authorizenetwebform_prepare_data($transaction_type, $nid, $field_value
$first_key = $flipped_map['x_first_name'];
$last_key = $flipped_map['x_last_name'];
// Get the donation type for quick reference.
$donation_type = $field_values[$type_key];
$data = array(
$transaction_type => array(
'merchantAuthentication' => array(
'name' => variable_get('authorizenetwebform_login', NULL),
'transactionKey' => variable_get('authorizenetwebform_transaction', NULL),
),
'refId' => $nid . '-' . time(),
),
);
// One-time payment.
if ($transaction_type == 'createTransactionRequest') {
$request_type = 'transactionRequest';
$data = array(
'createTransactionRequest' => array(
'merchantAuthentication' => array(
'name' => variable_get('authorizenetwebform_login', NULL),
'transactionKey' => variable_get('authorizenetwebform_transaction', NULL),
),
'refId' => $nid . '-' . time(),
'transactionRequest' => array(
'transactionType' => 'authCaptureTransaction',
'amount' => $amount,
'payment' => array(
'opaqueData' => array(
'dataDescriptor' => 'COMMON.ACCEPT.INAPP.PAYMENT',
'dataValue' => $field_values[$trans_key],
),
),
'profile' => array(
'createProfile' => TRUE,
),
'billTo' => array(
'firstName' => $field_values[$first_key],
'lastName' => $field_values[$last_key],
'company' => '',
'address' => '',
'city' => '',
'state' => '',
'zip' => '',
'country' => 'USA', // @todo add default country setting?
),
'customerIP' => $_SERVER['REMOTE_ADDR'],
'transactionSettings' => array(
'setting' => array(
'settingName' => 'testRequest',
'settingValue' => 'false',
),
),
$one_time_data = array(
'transactionType' => 'authCaptureTransaction',
'amount' => $amount,
'payment' => array(
'opaqueData' => array(
'dataDescriptor' => 'COMMON.ACCEPT.INAPP.PAYMENT',
'dataValue' => $field_values[$trans_key],
),
)
),
);
// Need to interrupt here because AuthNet expects this order.
if ($donation_type == 'subscription') {
$one_time_data['profile'] = array('createProfile' => TRUE);
}
$one_time_data['billTo'] = array(
'firstName' => $field_values[$first_key],
'lastName' => $field_values[$last_key],
'company' => '',
'address' => '',
'city' => '',
'state' => '',
'zip' => '',
'country' => 'USA', // @todo add default country setting?
);
$one_time_data['customerIP'] = $_SERVER['REMOTE_ADDR'];
$one_time_data['transactionSettings'] = array(
'setting' => array(
'settingName' => 'testRequest',
'settingValue' => 'false',
),
);
$request_type = 'transactionRequest';
$data[$transaction_type][$request_type] = $one_time_data;
}
// Recurring payment.
if ($transaction_type == 'ARBCreateSubscriptionRequest') {
$request_type = 'subscription';
$data = array(
'ARBCreateSubscriptionRequest' => array(
'merchantAuthentication' => array(
'name' => variable_get('authorizenetwebform_login', NULL),
'transactionKey' => variable_get('authorizenetwebform_transaction', NULL),
$tomorrow = new DateTime('tomorrow');
$start_date = $tomorrow->format('Y-m-d');
$subscription_data = array(
'name' => 'Recurring donation',
'paymentSchedule' => array(
'interval' => array(
'length' => 1,
'unit' => 'months',
),
'refId' => $nid . '-' . time(),
'subscription' => array(
'name' => 'Recurring donation',
'paymentSchedule' => array(
'interval' => array(
'length' => 1,
'unit' => 'months',
),
'startDate' => date('Y-m-d'),
'totalOccurrences' => 9999,
'trialOccurrences' => 1,
),
'amount' => $amount,
'trialAmount' => '0.00',
'payment' => array(
'opaqueData' => array(
'dataDescriptor' => 'COMMON.ACCEPT.INAPP.PAYMENT',
'dataValue' => $field_values[$trans_key],
),
),
'billTo' => array(
'firstName' => $field_values[$first_key],
'lastName' => $field_values[$last_key],
'company' => '',
'address' => '',
'city' => '',
'state' => '',
'zip' => '',
'country' => 'USA', // @todo add default country setting?
),
'startDate' => $start_date,
'totalOccurrences' => 9999,
'trialOccurrences' => 1,
),
'amount' => $amount,
'trialAmount' => '0.00',
'payment' => array(
'opaqueData' => array(
'dataDescriptor' => 'COMMON.ACCEPT.INAPP.PAYMENT',
'dataValue' => $field_values[$trans_key],
),
),
'billTo' => array(
'firstName' => $field_values[$first_key],
'lastName' => $field_values[$last_key],
'company' => '',
'address' => '',
'city' => '',
'state' => '',
'zip' => '',
'country' => 'USA', // @todo add default country setting?
),
);
$request_type = 'subscription';
$data[$transaction_type][$request_type] = $subscription_data;
}
// Add the optional customer's billing data, if present.
......@@ -893,7 +791,7 @@ function _authorizenetwebform_prepare_data($transaction_type, $nid, $field_value
}
// Add everything else as UserFields (API only supports One-Time transactions)
if ($transaction_type == 'one-time' && !empty($field_keys)) {
if ($donation_type == 'one-time' && !empty($field_keys)) {
$data[$transaction_type][$request_type]['userFields'] = array();
$data[$transaction_type][$request_type]['userFields']['userField'] = array();
$count = 1;
......@@ -918,3 +816,147 @@ function _authorizenetwebform_prepare_data($transaction_type, $nid, $field_value
return $data;
}
/**
* Handle the response from AuthNet.
*
* @param array $response_array
* Full response from AuthNet.
* @param int $nid
* Node ID for the webform being submitted.
* @param array $data
* Complete data sent to AuthNet - for debugging purposes.
*/
function _authorizenetwebform_handle_result($response_array, $nid, $data) {
if ($response_array['messages']['resultCode'] == 'Ok') {
$text = '';
$failure = FALSE;
$response_info = array();
// Extrat the response info we need for our records.
if (isset($response_array['transactionResponse'])) {
$response_info = $response_array['transactionResponse'];
}
// Decliend || Error
if (!empty($response_info) && isset($response_info['responseCode']) &&
($response_info['responseCode'] == 2 || $response_info['responseCode'] == 3)) {
$failure = TRUE;
}
else {
// Add subscription info.
if (array_key_exists('subscriptionId', $response_array)) {
$id = $response_array['subscriptionId'];
$text .= ' ' . t('Your subscription ID is @id', array('@id' => $id));
}
// Success! Set the message.
drupal_set_message('Thank you. Your payment has been processed.');
}
// Failure :( Set the form error.
if ($failure) {
if (!empty($response_info) && !empty($response_info['errors'])) {
foreach ($response_info['errors'] as $info) {
$code = $info['errorCode'];
$text = $info['errorText'];
// Log to watchdog.
$variables = array('@code' => $code, '@message' => $text);
watchdog('authorizenetwebform', 'transactionResponse error @code from Authorize.net: @message',
$variables, WATCHDOG_ERROR);
// Print to screen.
$string = $text . ' (Error code: ' . $code . ')';
drupal_set_message($string, 'error');
form_set_error(NULL, $string);
// Stop the submission.
$form_state['rebuild'] = TRUE;
}
}
form_set_error(NULL, $text);
// Stop the submission.
$form_state['rebuild'] = TRUE;
}
// Get Transaction ID Component ID: webform field => component ID.
$node = node_load($nid);
$flipped_map = _authorizenetwebform_get_key_mappings($nid, TRUE);
$webform_field_name = $flipped_map['x_trans_id'];
$component_ids = _authorizenetwebform_get_component_ids($node);
$trans_cid = $component_ids[$webform_field_name];
$response_code_options = array(
'1' => 'Approved',
'2' => 'Declined',
'3' => 'Error',
'4' => 'Held for Review',
);
$response_code = 'none';
$response_id = 'none';
$response_hash = 'none';
$response_cc_safe = 'none';
if (!empty($response_info)) {
if (isset($response_info['responseCode'])) {
$response_code_options[$response_info['responseCode']];
}
$response_id = $response_info['transId'];
$response_hash = $response_info['transHash'];
$response_cc_safe = $response_info['accountNumber'];
// Update the webform submission Transaction ID.
$form_state['values']['submitted'][$trans_cid] = $response_id;
// Log some response data to watchdog, if it exists.
$message = 'Transaction !code. Transaction ID: !id. Transaction Hash: !hash. Credit card: !cc';
$variables = array(
'!code' => $response_code,
'!id' => $response_id,
'!hash' => $response_hash,
'!cc' => $response_cc_safe,
);
watchdog('authorizenetwebform', $message, $variables, WATCHDOG_NOTICE);
}
// Record the entire response if debug mode is on.
if (variable_get('authorizenetwebform_debug', FALSE)) {
// @todo: Save this data into a more permanent location than watchdog?
$message = 'The data set sent to Auth.Net follows:<br/> !string';
$string = '<pre>' . print_r($data, TRUE) . '</pre>';
$variables = array('!string' => $string);
watchdog('authorizenetwebform', $message, $variables, WATCHDOG_INFO);
$message = 'The complete response string from Auth.Net follows:<br/> !string';
$string = '<pre>' . print_r($response_array, TRUE) . '</pre>';
$variables = array('!string' => $string);
watchdog('authorizenetwebform', $message, $variables, WATCHDOG_INFO);
// Also print response to screen if devel is enabled.
if (module_exists('devel')) {
dpm($response_array);
}
}
}
elseif ($response_array['messages']['resultCode'] == 'Error') {
foreach ($response_array['messages']['message'] as $info) {
$code = $info['code'];
$text = $info['text'];
// Log to watchdog.
$variables = array('@code' => $code, '@message' => $text);
watchdog('authorizenetwebform', 'Error @code from Authorize.net: @message',
$variables, WATCHDOG_ERROR);
// Print to screen.
drupal_set_message($code . ': ' . $text, 'error');
form_set_error(NULL, $code . ': ' . $text);
// Stop the submission.
$form_state['rebuild'] = TRUE;
}
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment