Jump to content

I am trying to update database after I run ajax curl for Transaction Express gateway, it fails


WebsiteInteract

Recommended Posts

OK I have a file called process.php that will run a Transaction Express transaction.  It works but I wanted to add ability to update a database in the transaction but when I do this it doesn't process.  What is happening is my checkbox form fields are called ad_choice[] and I set up to write the values of each form field to be something like name_id86.  Well, what i am trying to do is to count the number of checked boxes, put them into an array, send each id to curl and update database field called "available" from 1 to 0 upon a successful card transaction.  This is my process.php code and the code at the end is supposed to do everything but it fails.  I got a similar thing to work but it wasn't incorporated into a gateway so I am wondering if the fact that I am tring to run curl twice is causing my issues.  My code starts where it says "THIS IS THE ADDED CODE.."  I can supply the code from the other two files if necessary but I was just wondering if I sent my headers or something that could be stopping this from transacting and writing to database.  Someone told me I needed to use sessions but I really did not know how to go about that. 

<?php
function generateEmailTransaction($transactionId, $invoiceNumber) {
    $emailMapContact = array(
        "full_name" => "Name:",
        "email" => "Email:",
        "address" => "Address",
        "city" => "City:",
        "state" => "State:",
        "zip" => "Zip:",
    );
    $contact = 'We have received your generous donation of $' .  $_POST['result'] . ' to this years  Dedication.
Thank you for your participation.
';
    $contact .= "Transaction details:\n";
    $contact .= "-------------------- \n\n";
    $contact .= 'Transaction Amount: $' . $_POST['result'] . "\n";
    $contact .= 'Transaction ID: ' . $transactionId . "\n";
    $contact .= 'Invoice: ' . $invoiceNumber . "\n\n";
    $contact .= "Personal details \n";
    $contact .= "---------------- \n\n";
    foreach ($emailMapContact as $key => $value) {
        if ( ! empty($_POST[$key]) ) {
            $contact .= $value . "\n";
            $contact .= $_POST[$key] . "\n\n";
        }
    }
    $emailMapContactPhone = array(
        "telephone_area_code" => "Phone:",
        "phone" => "Phone:",
        "phone2" => "Phone:",
    );
    $contactPhone = '';
    foreach ($emailMapContactPhone as $key => $value) {
        if ( ! empty($_POST[$key]) ) {
            if ( $key === 'phone2' ) {
                $contactPhone .= $_POST[$key];
            } else {
                $contactPhone .= $_POST[$key] . " - ";
            }
        }
    }
    $contact .= "Phone: \n";
    $contact .= $contactPhone . "\n\n";
    $emailMapProduct = array(
        "ad_choice" => "Dedication Chosen:"
    );
    $contact .= "Product details \n";
    $contact .= "--------------- \n\n";
    $dedi = $_POST['ad_choice'];
    $dedic = '';
    foreach ($dedi as $valueded) {
            $contact .= 'Dedication: '.$valueded. "\n";
    }
    return $contact;
}
function handleSuccess($transactionId)
{
    $invoiceNumber = "INV-" . time() . "-" . rand(10000, 99999);
    $emailBody = generateEmailTransaction($transactionId, $invoiceNumber);
    $dir = __DIR__ . '/transactions';
    if ( ! file_exists($dir) ) {
        mkdir($dir);
        file_put_contents($dir . '/index.html', "<!-- silence is golden -->");
    }
    file_put_contents(__DIR__ . '/transactions/' . $invoiceNumber . '.txt', $emailBody);
    //to admin
    // mail('name@domain.com', 'Admin Confirmation Receipt', $emailBody);
   // mail(chris@domain.com', 'Admin Confirmation Receipt', $emailBody);
    //to user
    mail($_POST['email'], 'Confirmation Receipt', $emailBody);
    echo json_encode(
        array(
            'success' => true, 
            'transaction_id' => $transactionId
        )
    );
   // ----------------------------------------- //
}
function handleError($responseCode , $err)
{
    $message = '----Something went wrong, please check your credit card credentials and try again</br> or contact us for assistance at j.ze@domain.com if problems persists.<br/>';
    if(isset($err))
    {
       $ded = $_POST['ad_choice'];
       $dedicated = '';
       foreach ($ded as $value) {
               $dedicated .= $value;
       }
       $message  .= 'Card# (This info only shows during error testing)'."<br>\n".'PLEASE CHECK TO SEE IF ALL INFO IS CORRECT BELOW:'."\n"."<br><br>\n".
       $message .= $err.'Card# (This info only shows during error testing)'."<br>\n".'PLEASE CHECK TO SEE IF ALL INFO IS CORRECT BELOW:'."\n".$_POST['card_number']."<br><br>\n".
       'Expire: '.$_POST['expiry_month'].'/'.$_POST['expiry_year']."\n".
       'Card Holder Name: '.$_POST['card_holder_name']."\n".       
       'CVV Code: '.$_POST['security_code']."\n".
       'Email:'.$_POST['email']."<br>\n".
       'Phone: '.$_POST['telephone_area_code'] . $_POST['phone'] . $_POST['phone2']."\n".
       'Address:'.$_POST['address']."\n".
       'City:'.$_POST['city'].','.$_POST['state'].' '.$_POST['zip']."\n".
       'AMOUNT: $'.$_POST['result']."<br><br>\n\n".
       'DEDICATIONS: '.$dedicated;
    }
    echo json_encode(
        array(
            'success' => false, 
            'response_code' => $responseCode, 
            'message' =>  $message 
        )
    );
}
function postPayment()
{
    $url= "https://post.transactionexpress.com/PostMerchantService.svc/CreditCardSale";
    $gateway =  '--------------';
    $regkey = '--------------';
    $year = $_POST['expiry_year'];
    if (strlen($year) == 4) 
    {
        $year = substr($year,2,2);
    }
    $fields= array('GatewayID' => $gateway, 
          'RegKey' => $regkey, 
          'IndustryCode'=>'2', 
          'AccountNumber'=>$_POST['card_number'], 
          'CVV2'=>$_POST['security_code'], 
          'ExpirationDate'=> $year . $_POST['expiry_month'] , 
          'Track1Data'=>'', 
          'Track2Data'=>'', 
          'Amount'=>$_POST['result'], 
          'TaxIndicator'=>'',
          'TaxAmount'=>'',
          'PONumber'=>'',
          'ShipToZip'=>$_POST['zip'],
          'CustRefID'=>'',
          'FullName'=>$_POST['card_holder_name'], 
          'Address1'=>$_POST['address'],
          'Address2'=>'',
          'City'=>$_POST['city'],
          'State'=>$_POST['state'],
          'Zip'=>$_POST['zip'], 
          'PhoneNumber'=>$_POST['telephone_area_code'] . $_POST['phone'] . $_POST['phone2'],
          'Email'=>$_POST['email']
          );
    $fields_string= http_build_query($fields);
    //set the url, number of POST vars, POST data
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    $response = curl_exec($ch);
    // Then, after your curl_exec call:
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    curl_close($ch);
    parse_str(trim($body,'"') , $output);
    if (isset($output['ResponseCode']))
    {
       if ($output['ResponseCode']==0 && isset($output['tranNr'] ))
       {
           handleSuccess($output['tranNr']);
       } 
       else 
       {
           handleError($output['ResponseCode'], '');
       }
    } 
    else if (isset($output['ErrorCode']))
    {
        handleError($output['ErrorCode'], $output['ErrorMessage']);
    }
    else
    {
    	handleError('','');
    }
}
//handleSuccess("test1000");
postPayment();


//// THIS IS THE ADDED CODE THAT TAKES THE SEPERATE IDS AND COUNTS THEM AND RESUBMITS TO UPDATE TO DATABASE
     $ids_submitted = $_POST['ad_choice'];
     $ded_array = $ids_submitted;
     $dedicate_value = '';
     foreach ($ded_array as $valuededicated) {
        $dedicate_value .= $valuededicated. "|";
     }
     $dv = explode ("__id-", $dedicate_value);  
     $dv = implode("|",$dv);
     // now we can explode once again and take the odd numbered indexes in array once done. 
     $dv = explode('|',$dv);
     $val2 ='';
     foreach ($dv as $key => $value) {
    	if($key % 2 == 0) {
           // printf("%d is even.", $key);
    	   // ignore even lines
    	} else {
            // echo value of even lines only - the id numbers
    		$value2 = $value.',';
    		$val2 .= $value2;
    	}
     }
    $val2 = rtrim($val2,',');   
    $val2= explode (",", $val2);  
    $val3 =''; 
    $count = count($val2);
    foreach ($val2 as $key => $value) {
       $newnum = $key + 1;
  	   $val3 .= 'id'.$newnum.'='.$value. '&';       
    }
    //we now have all the ids in the array
    $val3 = rtrim($val3,'&');
   //extract data from the post
   //set POST variables
    $url = 'https://domain.com/y/update-availability.php';
    $fields = array(
	'count_ids' => urlencode($count),
	'available' => urlencode($val3)
    );
    //url-ify the data for the POST
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    $fields_string = rtrim($fields_string, '&');
   //open connection
   $ch = curl_init();
   //set the url, number of POST vars, POST data
   curl_setopt($ch,CURLOPT_URL, $url);
   curl_setopt($ch,CURLOPT_POST, count($fields));
   curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
   //execute post
   $result = curl_exec($ch);
  //close connection
   curl_close($ch);  */
?>


 

Link to comment
Share on other sites

If I remove (or comment out) this code section and below.. the script works.  I know I am doing something wrong but I cant seem to figure it out.  Any ideas?  

//// THIS IS THE ADDED CODE THAT TAKES THE SEPERATE IDS AND COUNTS THEM AND RESUBMITS TO UPDATE TO DATABASE
Link to comment
Share on other sites

The code you've posted doesn't have anything to do with a database. You're making a curl call to update-availability.php. If that file is supposed to update a database value, we'd need to see the code in that file.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.