Jump to content

timestamp on AddTransaction


Recommended Posts

I have WHMCS set on localisation to YYYY-mm-DD

In our API call which has been working for years,  as YYYY-MM-DD. I upgraded to PHP 8.2 FPM and WHMCS 8.13.1 (from 8.11), and now the date in the DB is the date of the API call and not the date I am sending in the postdata. 

I tried changing the date format in settings/general/localisation

I have timezone in php set to Africa/Johannesburg

 

Am I chasing my own tail or is there a regression

 

I see in the changelog there is Correct date timestamp of refund transactions (Also known as: CORE-19688)

thanks

Link to comment
Share on other sites

17 minutes ago, WHMCS John said:

Hi @Walking with me,

1. Which API command are you experiencing this with?

2. Which parameter is affected? Please can you provide an example of the current data and for comparison the format you were expecting.

1.  AddTransaction

2. the date sent is now current date time and not value sent 

 

 

Link to comment
Share on other sites

1 hour ago, WHMCS John said:

Hi @Walking with me,

1. Which API command are you experiencing this with?

2. Which parameter is affected? Please can you provide an example of the current data and for comparison the format you were expecting.

Post Data: array(11) {
  ["identifier"]=>
  string(32) "....1"
  ["secret"]=>
  string(32) "C....O"
  ["action"]=>
  string(14) "AddTransaction"
  ["responsetype"]=>
  string(4) "json"
  ["userid"]=>
  string(1) "1"
  ["amountin"]=>
  string(4) "1.00"
  ["date"]=>
  string(10) "2025-07-03"
  ["credit"]=>
  string(4) "true"
  ["description"]=>
  string(15) "ImportST: blha2"
  ["transid"]=>
  string(46) "1098B5B1-856B-1B0E-18A6-657B2FC10318"
  ["paymentmethod"]=>
  string(12) "banktransfer"
}

tblaccounts:

id    userid    currency    gateway    date    description    amountin    fees    amountout    rate    transid
2257    1    0    banktransfer    2025-07-07 17:45:48    ImportST: blha2    1.00    0.00    0.00    1.00000    1098B5B1-856B-1B0E-18A6-657B2FC10318

tblconfiguration

id    setting    value    created_at    updated_at
15    DateFormat    YYYY-MM-DD    NULL    2025-07-06 22:05:10

 

the date is the date of the api call not the transaction date, worked fine in previous versions.

Link to comment
Share on other sites

On 7/14/2025 at 6:17 PM, pRieStaKos said:

Use Carbon for setting the formatting, in your code (https://carbon.nesbot.com/docs/#api-formatting)

Provide example to assist you any further.

 
Thanks,  have used Carbon but still get the same result.  I have a workaround to do a sql date update as below which is far from ideal.
 
<?php
 
if (!defined("WHMCS")) {
die("This file cannot be accessed directly");
}
 
require_once __DIR__ . '/../../../init.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/../../../vendor/autoload.php';
use WHMCS\Database\Capsule;
use Carbon\Carbon;
 
$moduleName = 'csvpaymentimport';
$moduleConfiguration = Capsule::table('tbladdonmodules')->where('module', $moduleName)->pluck('value', 'setting');
$moduleVersion = $moduleConfiguration['version'] ?? 'Unknown';
 
echo '<h2>Upload Payment  Register CSV File</h2>';
echo '<h3>This must be correct - a mistake in CSV will do weird things!</h3>';
echo '<h4>Module Version: ' . htmlspecialchars($moduleVersion) . '</h4>';
echo '<p>Current system date/time: ' . date(DATE_RFC2822) . '<br />';
echo 'timezone: ' . date_default_timezone_get() . '</p>';
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '?module=mcitpayment&action=upload" enctype="multipart/form-data">';
echo '<input type="file" name="fileToUpload" id="fileToUpload"><br />';
echo '<input type="submit" class="btn btn-primary" value="Upload File and process" name="submit">';
echo '<br />This may take a while to process<br />';
echo '</form>';
 
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
$fileTmpPath = $_FILES['fileToUpload']['tmp_name'];
$fileName = $_FILES['fileToUpload']['name'];
$fileType = $_FILES['fileToUpload']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
 
$allowedfileExtensions = ['csv'];
if (in_array($fileExtension, $allowedfileExtensions)) {
if ($_FILES['fileToUpload']['error'] === UPLOAD_ERR_OK) {
$file = fopen($fileTmpPath, 'r');
if ($file === false) {
echo "Failed to open uploaded file.";
return;
}
fgetcsv($file);
 
if ($moduleConfiguration['debug']) {
 
echo '<pre>Module Config: ';
var_dump($moduleConfiguration);
echo '</pre>';
}
 
while (($row = fgetcsv($file)) !== FALSE) {
$clientId = $row[0];
$csvdate = str_replace('/', '-', $row[1]);
try {
$carbonRef = Carbon::now('Africa/Johannesburg');
$carbonized = $carbonRef->carbonize($csvdate);
$csvdateFormatted = $carbonized->format('Y-m-d H:i:s.u');
} catch (Exception $e) {
$csvdateFormatted = $csvdate;
}
$csvDescription = $row[2];
$amount = $row[3];
$status = $row[4];
$guid = $row[5];
 
 
if ($status !== 'a') {
continue;
}
 
// Clean the amount by removing spaces and unwanted characters
$amount = trim($amount);
$amount = str_replace(' ', '', $amount);
$amount = str_replace(',', '', $amount);
$amount = preg_replace('/[^\d\.]/', '', $amount);
 
$postData = [
'identifier' => $moduleConfiguration['identifier'],
'secret' => $moduleConfiguration['secret'],
'action' => 'AddTransaction',
'responsetype' => 'json',
'userid' => $clientId,
'amountin' => $amount,
'date' => $csvdateFormatted,
'credit' => 'true',
'description' => 'ImportST: ' . $csvDescription,
'transid' => $guid,
'paymentmethod' => 'banktransfer',
];
 
if ($moduleConfiguration['debug']) {
echo '<pre>Post Data: ';
var_dump($postData);
echo ", LogDir: ";
$logDirectory = dirname(__DIR__, 4) . '/logs/';
$dateToday = date("Y-m-d");
$logFile = $logDirectory . "api_transaction_log_{$dateToday}.txt";
echo $logFile;
echo '</pre>';
}
 
$response = callApi($postData, $moduleConfiguration);
if ($moduleConfiguration['debug']) {
echo '<pre>API Response Dump:';
var_dump($response);
echo '</pre>';
}
if (isset($response['result']) && $response['result'] == 'success') {
echo "Transaction added successfully for client ID $clientId <br>";
 
// Only update SQL date if enabled in module configuration
if (!empty($moduleConfiguration['sql_date_update'])) {
try {
$dateForDb = date('Y-m-d', strtotime($csvdateFormatted));
Capsule::table('tblaccounts')
->where('transid', $guid)
->update(['date' => $dateForDb]);
if ($moduleConfiguration['debug']) {
echo "Updated transaction date for transid $guid to $dateForDb<br>";
}
} catch (\Exception $e) {
echo "Failed to update transaction date for client ID $clientId: " . $e->getMessage() . "<br>";
}
}
 
} else {
echo "Failed to add transaction for client ID $clientId: " . json_encode($response) . "<br>";
}
 
writeToLog($clientId, $csvdate, $amount, isset($response['transactionid']) ? $response['transactionid'] : '', $postData);
}
fclose($file);
} else {
echo "Error uploading file: " . $_FILES['fileToUpload']['error'];
}
} else {
echo "Upload failed, unsupported file type.";
}
} else {
echo "<br />No file uploaded yet or an error occurred.";
}
 
function callApi($postData, $moduleConfiguration) {
$ch = curl_init();
$customHost = $moduleConfiguration['customhost'];
$customIP = $moduleConfiguration['api_ip'];
$resolveString = "{$customHost}:443:{$customIP}";
 
curl_setopt($ch, CURLOPT_URL, $moduleConfiguration['api_url']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Host: $customHost"]);
curl_setopt($ch, CURLOPT_RESOLVE, [$resolveString]);
 
if ($moduleConfiguration['debug']) {
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
}
 
$response = curl_exec($ch);
$info = curl_getinfo($ch);
 
if ($moduleConfiguration['debug']) {
if ($response === false) {
echo "cURL error: " . curl_error($ch) . "\n";
}
rewind($verbose);
echo "cURL verbose information:\n" . stream_get_contents($verbose) . "\n";
}
 
if (curl_error($ch)) {
echo 'cURL connection error: ' . curl_error($ch) . "\n";
}
 
curl_close($ch);
 
if ($moduleConfiguration['debug']) {
echo "cURL info: \n";
print_r($info);
echo "API Response: \n";
print_r($response);
}
 
$jsonData = json_decode($response, true);
if ($moduleConfiguration['debug']) {
echo "Decoded JSON Response:\n";
var_dump($jsonData);
}
return $jsonData;
}
 
function writeToLog($clientId, $date, $amount, $transactionId, $postData) {
 
if (isset($_GET['debuglog']) || (isset($postData['debug']) && $postData['debug'])) {
$logDirectory = dirname(__DIR__, 4) . '/logs/';
$dateToday = date("Y-m-d");
$logFile = $logDirectory . "api_transaction_log_{$dateToday}.txt";
echo "<pre>writeToLog called. LogDir: $logDirectory, LogFile: $logFile</pre>";
}
$logDirectory = dirname(__DIR__, 4) . '/logs/';
$dateToday = date("Y-m-d");
$logFile = $logDirectory . "api_transaction_log_{$dateToday}.txt";
 
if (!file_exists($logDirectory)) {
mkdir($logDirectory, 0750, true);
}
 
$timeStamp = date("Y-m-d H:i:s");
$postDataString = json_encode($postData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$logEntry = "{$timeStamp} - Success: Client ID {$clientId}, Date: {$date}, Amount: {$amount}, Transaction ID: {$transactionId}\nPOST DATA: {$postDataString}\n";
 
file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
}
?>
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use & Guidelines and understand your posts will initially be pre-moderated