diff --git a/agent/post/payment.php b/agent/post/payment.php index 24cacf91..0cb8cc0f 100644 --- a/agent/post/payment.php +++ b/agent/post/payment.php @@ -377,8 +377,6 @@ if (isset($_POST['add_payment_stripe'])) { $account_id = intval($row['payment_provider_account']); $expense_category_id = intval($row['payment_provider_expense_category']); $expense_vendor_id = intval($row['payment_provider_expense_vendor']); - $expense_percentage_fee = floatval($row['payment_provider_expense_percentage_fee']); - $expense_flat_fee = floatval($row['payment_provider_expense_flat_fee']); $payment_provider_client = escapeSql($row['payment_provider_client']); $saved_payment_method = escapeSql($row['saved_payment_provider_method']); $saved_payment_description = escapeSql($row['saved_payment_description']); @@ -412,6 +410,7 @@ if (isset($_POST['add_payment_stripe'])) { 'off_session' => true, 'confirm' => true, 'description' => $pi_description, + 'expand' => ['latest_charge.balance_transaction'], 'metadata' => [ 'itflow_client_id' => $client_id, 'itflow_client_name' => $client_name, @@ -488,10 +487,16 @@ if (isset($_POST['add_payment_stripe'])) { $extended_log_desc = '(DEV MODE)'; } - // Create Stripe payment gateway fee as an expense (if configured) + // Create actual Stripe gateway fee as an expense (if configured) if ($expense_vendor_id > 0 && $expense_category_id > 0) { - $gateway_fee = round($invoice_amount * $expense_percentage_fee + $expense_flat_fee, 2); - mysqli_query($mysqli,"INSERT INTO expenses SET expense_date = '$pi_date', expense_amount = $gateway_fee, expense_currency_code = '$invoice_currency_code', expense_account_id = $account_id, expense_vendor_id = $expense_vendor_id, expense_client_id = $client_id, expense_category_id = $expense_category_id, expense_description = 'Stripe Transaction for Invoice $invoice_prefix$invoice_number In the Amount of $balance_to_pay', expense_reference = 'Stripe - $pi_id $extended_log_desc'"); + $stripe_fee = getStripeGatewayFee($payment_intent); + if ($stripe_fee) { + $gateway_fee = floatval($stripe_fee['fee']); + $gateway_fee_currency = escapeSql($stripe_fee['currency']); + mysqli_query($mysqli,"INSERT INTO expenses SET expense_date = '$pi_date', expense_amount = $gateway_fee, expense_currency_code = '$gateway_fee_currency', expense_account_id = $account_id, expense_vendor_id = $expense_vendor_id, expense_client_id = $client_id, expense_category_id = $expense_category_id, expense_description = 'Stripe fee for Invoice $invoice_prefix$invoice_number payment of $balance_to_pay', expense_reference = 'Stripe - $pi_id $extended_log_desc'"); + } else { + logApp("Stripe", "warning", "Balance transaction unavailable for $pi_id - fee expense not recorded for invoice ID $invoice_id"); + } } // Notify/log @@ -514,192 +519,6 @@ if (isset($_POST['add_payment_stripe'])) { } -/* -if (isset($_GET['add_payment_stripe'])) { - - validateCSRFToken($_GET['csrf_token']); - - enforceUserPermission('module_sales', 2); - enforceUserPermission('module_financial', 2); - - $invoice_id = intval($_GET['invoice_id']); - - // Get invoice details - $sql = mysqli_query($mysqli,"SELECT * FROM invoices - LEFT JOIN clients ON invoice_client_id = client_id - LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1 - WHERE invoice_id = $invoice_id" - ); - $row = mysqli_fetch_assoc($sql); - $invoice_number = intval($row['invoice_number']); - $invoice_status = escapeSql($row['invoice_status']); - $invoice_amount = floatval($row['invoice_amount']); - $invoice_prefix = escapeSql($row['invoice_prefix']); - $invoice_number = intval($row['invoice_number']); - $invoice_url_key = escapeSql($row['invoice_url_key']); - $invoice_currency_code = escapeSql($row['invoice_currency_code']); - $client_id = intval($row['client_id']); - $client_name = escapeSql($row['client_name']); - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - $contact_phone = escapeSql(formatPhoneNumber($row['contact_phone'], $row['contact_phone_country_code'])); - $contact_extension = preg_replace("/[^0-9]/", '',$row['contact_extension']); - $contact_mobile = escapeSql(formatPhoneNumber($row['contact_mobile'], $row['contact_mobile_country_code'])); - - // Get ITFlow company details - $sql = mysqli_query($mysqli,"SELECT * FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_country = escapeSql($row['company_country']); - $company_address = escapeSql($row['company_address']); - $company_city = escapeSql($row['company_city']); - $company_state = escapeSql($row['company_state']); - $company_zip = escapeSql($row['company_zip']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - $company_email = escapeSql($row['company_email']); - $company_website = escapeSql($row['company_website']); - - // Sanitize Config vars from get_settings.php - $config_invoice_from_name = escapeSql($config_invoice_from_name); - $config_invoice_from_email = escapeSql($config_invoice_from_email); - - // Get Client Stripe details - $stripe_client_details = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM client_stripe WHERE client_id = $client_id LIMIT 1")); - $stripe_id = escapeSql($stripe_client_details['stripe_id']); - $stripe_pm = escapeSql($stripe_client_details['stripe_pm']); - - // Sanity checks - if (!$config_stripe_enable || !$stripe_id || !$stripe_pm) { - flashAlert("Stripe not enabled or no client card saved", 'error'); - redirect(); - } elseif ($invoice_status !== 'Sent' && $invoice_status !== 'Viewed') { - flashAlert("Invalid invoice state (draft/partial/paid/not billable)", 'error'); - redirect(); - } elseif ($invoice_amount == 0) { - flashAlert("Invalid invoice amount", 'error'); - redirect(); - } - - // Initialize Stripe - require_once __DIR__ . '/../libs/stripe-php/init.php'; - $stripe = new \Stripe\StripeClient($config_stripe_secret); - - $balance_to_pay = round($invoice_amount, 2); - $pi_description = "ITFlow: $client_name payment of $invoice_currency_code $balance_to_pay for $invoice_prefix$invoice_number"; - - // Create a payment intent - try { - $payment_intent = $stripe->paymentIntents->create([ - 'amount' => intval($balance_to_pay * 100), // Times by 100 as Stripe expects values in cents - 'currency' => $invoice_currency_code, - 'customer' => $stripe_id, - 'payment_method' => $stripe_pm, - 'off_session' => true, - 'confirm' => true, - 'description' => $pi_description, - 'metadata' => [ - 'itflow_client_id' => $client_id, - 'itflow_client_name' => $client_name, - 'itflow_invoice_number' => $invoice_prefix . $invoice_number, - 'itflow_invoice_id' => $invoice_id, - ] - ]); - - // Get details from PI - $pi_id = escapeSql($payment_intent->id); - $pi_date = date('Y-m-d', $payment_intent->created); - $pi_amount_paid = floatval(($payment_intent->amount_received / 100)); - $pi_currency = strtoupper(escapeSql($payment_intent->currency)); - $pi_livemode = $payment_intent->livemode; - - } catch (Exception $e) { - $error = $e->getMessage(); - error_log("Stripe payment error - encountered exception during payment intent for invoice ID $invoice_id / $invoice_prefix$invoice_number: $error"); - logApp("Stripe", "error", "Exception during PI for invoice ID $invoice_id: $error"); - } - - if ($payment_intent->status == "succeeded" && intval($balance_to_pay) == intval($pi_amount_paid)) { - - // Update Invoice Status - mysqli_query($mysqli, "UPDATE invoices SET invoice_status = 'Paid' WHERE invoice_id = $invoice_id"); - - // Add Payment to History - mysqli_query($mysqli, "INSERT INTO payments SET payment_date = '$pi_date', payment_amount = $pi_amount_paid, payment_currency_code = '$pi_currency', payment_account_id = $config_stripe_account, payment_method = 'Stripe', payment_reference = 'Stripe - $pi_id', payment_invoice_id = $invoice_id"); - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Paid', history_description = 'Online Payment added (agent)', history_invoice_id = $invoice_id"); - - // Email receipt - if (!empty($config_smtp_provider)) { - $subject = "Payment Received - Invoice $invoice_prefix$invoice_number"; - $body = "Hello $contact_name,

We have received online payment for the amount of " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . " for invoice $invoice_prefix$invoice_number. Please keep this email as a receipt for your records.

Amount Paid: " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . "

Thank you for your business!


--
$company_name - Billing Department
$config_invoice_from_email
$company_phone"; - - // Queue Mail - $data = [ - [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body, - ] - ]; - - // Email the internal notification address too - if (!empty($config_invoice_paid_notification_email)) { - $subject = "Payment Received - $client_name - Invoice $invoice_prefix$invoice_number"; - $body = "Hello,

This is a notification that an invoice has been paid in ITFlow. Below is a copy of the receipt sent to the client:-

--------

Hello $contact_name,

We have received online payment for the amount of " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . " for invoice $invoice_prefix$invoice_number. Please keep this email as a receipt for your records.

Amount Paid: " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . "

Thank you for your business!


--
$company_name - Billing Department
$config_invoice_from_email
$company_phone"; - - $data[] = [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $config_invoice_paid_notification_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body, - ]; - } - - $mail = addToMailQueue($data); - - // Email Logging - $email_id = mysqli_insert_id($mysqli); - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Payment Receipt sent to mail queue ID: $email_id!', history_invoice_id = $invoice_id"); - logAudit("Invoice", "Payment", "Payment receipt for invoice $invoice_prefix$invoice_number queued to $contact_email Email ID: $email_id", $client_id, $invoice_id); - } - - // Log info - $extended_log_desc = ''; - if (!$pi_livemode) { - $extended_log_desc = '(DEV MODE)'; - } - - // Create Stripe payment gateway fee as an expense (if configured) - if ($config_stripe_expense_vendor > 0 && $config_stripe_expense_category > 0) { - $gateway_fee = round($invoice_amount * $config_stripe_percentage_fee + $config_stripe_flat_fee, 2); - mysqli_query($mysqli,"INSERT INTO expenses SET expense_date = '$pi_date', expense_amount = $gateway_fee, expense_currency_code = '$invoice_currency_code', expense_account_id = $config_stripe_account, expense_vendor_id = $config_stripe_expense_vendor, expense_client_id = $client_id, expense_category_id = $config_stripe_expense_category, expense_description = 'Stripe Transaction for Invoice $invoice_prefix$invoice_number In the Amount of $balance_to_pay', expense_reference = 'Stripe - $pi_id $extended_log_desc'"); - } - - // Notify/log - appNotify("Invoice Paid", "Invoice $invoice_prefix$invoice_number automatically paid", "invoice.php?invoice_id=$invoice_id", $client_id); - logAudit("Invoice", "Payment", "$session_name initiated Stripe payment amount of " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . " added to invoice $invoice_prefix$invoice_number - $pi_id $extended_log_desc", $client_id, $invoice_id); - triggerCustomAction('invoice_pay', $invoice_id); - - flashAlert("Payment amount " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . " added"); - - redirect(); - - } else { - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Payment failed', history_description = 'Stripe pay failed due to payment error', history_invoice_id = $invoice_id"); - - logAudit("Invoice", "Payment", "Failed online payment amount of invoice $invoice_prefix$invoice_number due to Stripe payment error", $client_id, $invoice_id); - flashAlert("Payment failed", 'error'); - - redirect(); - } - -} -*/ - if (isset($_POST['add_bulk_payment'])) { validateCSRFToken($_POST['csrf_token']); diff --git a/client/post.php b/client/post.php index 268e229f..7fca4447 100644 --- a/client/post.php +++ b/client/post.php @@ -550,8 +550,6 @@ if (isset($_GET['add_payment_by_provider'])) { $account_id = intval($row['payment_provider_account']); $expense_category_id = intval($row['payment_provider_expense_category']); $expense_vendor_id = intval($row['payment_provider_expense_vendor']); - $expense_percentage_fee = floatval($row['payment_provider_expense_percentage_fee']); - $expense_flat_fee = floatval($row['payment_provider_expense_flat_fee']); $payment_provider_client = escapeSql($row['payment_provider_client']); $saved_payment_method = escapeSql($row['saved_payment_provider_method']); $saved_payment_description = escapeSql($row['saved_payment_description']); @@ -593,6 +591,7 @@ if (isset($_GET['add_payment_by_provider'])) { 'off_session' => true, 'confirm' => true, 'description' => $pi_description, + 'expand' => ['latest_charge.balance_transaction'], 'metadata' => [ 'itflow_client_id' => $client_id, 'itflow_client_name' => $client_name, @@ -669,10 +668,16 @@ if (isset($_GET['add_payment_by_provider'])) { $extended_log_desc = '(DEV MODE)'; } - // Create Stripe payment gateway fee as an expense (if configured) + // Create actual Stripe gateway fee as an expense (if configured) if ($expense_vendor_id > 0 && $expense_category_id > 0) { - $gateway_fee = round($invoice_amount * $expense_percentage_fee + $expense_flat_fee, 2); - mysqli_query($mysqli,"INSERT INTO expenses SET expense_date = '$pi_date', expense_amount = $gateway_fee, expense_currency_code = '$invoice_currency_code', expense_account_id = $account_id, expense_vendor_id = $expense_vendor_id, expense_client_id = $client_id, expense_category_id = $expense_category_id, expense_description = 'Stripe Transaction for Invoice $invoice_prefix$invoice_number In the Amount of $balance_to_pay', expense_reference = 'Stripe - $pi_id $extended_log_desc'"); + $stripe_fee = getStripeGatewayFee($payment_intent); + if ($stripe_fee) { + $gateway_fee = floatval($stripe_fee['fee']); + $gateway_fee_currency = escapeSql($stripe_fee['currency']); + mysqli_query($mysqli,"INSERT INTO expenses SET expense_date = '$pi_date', expense_amount = $gateway_fee, expense_currency_code = '$gateway_fee_currency', expense_account_id = $account_id, expense_vendor_id = $expense_vendor_id, expense_client_id = $client_id, expense_category_id = $expense_category_id, expense_description = 'Stripe fee for Invoice $invoice_prefix$invoice_number payment of $balance_to_pay', expense_reference = 'Stripe - $pi_id $extended_log_desc'"); + } else { + logApp("Stripe", "warning", "Balance transaction unavailable for $pi_id - fee expense not recorded for invoice ID $invoice_id"); + } } // Notify/log diff --git a/cron/cron.php b/cron/cron.php index 2c8711bd..744f803c 100644 --- a/cron/cron.php +++ b/cron/cron.php @@ -820,8 +820,6 @@ while ($row = mysqli_fetch_assoc($sql_recurring_payments)) { $account_id = intval($saved_payment['payment_provider_account']); $expense_category_id = intval($saved_payment['payment_provider_expense_category']); $expense_vendor_id = intval($saved_payment['payment_provider_expense_vendor']); - $expense_percentage_fee = floatval($saved_payment['payment_provider_expense_percentage_fee']); - $expense_flat_fee = floatval($saved_payment['payment_provider_expense_flat_fee']); $saved_payment_description = escapeSql($saved_payment['saved_payment_description']); $stripe_payment_method_id = $saved_payment['saved_payment_provider_method']; @@ -853,6 +851,7 @@ while ($row = mysqli_fetch_assoc($sql_recurring_payments)) { 'off_session' => true, 'confirm' => true, 'description' => $pi_description, + 'expand' => ['latest_charge.balance_transaction'], 'metadata' => [ 'itflow_client_id' => $client_id, 'itflow_client_name' => $client_name, @@ -885,10 +884,16 @@ while ($row = mysqli_fetch_assoc($sql_recurring_payments)) { mysqli_query($mysqli, "INSERT INTO payments SET payment_date = '$pi_date', payment_amount = $pi_amount_paid, payment_currency_code = '$pi_currency', payment_account_id = $account_id, payment_method = 'Stripe', payment_reference = 'Stripe - $pi_id', payment_invoice_id = $invoice_id"); mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Paid', history_description = 'Online Payment added (autopay)', history_invoice_id = $invoice_id"); - // EXPENSE: Stripe gateway fee as an expense (if configured) + // EXPENSE: Actual Stripe gateway fee as an expense (if configured) if ($expense_vendor_id > 0 && $expense_category_id > 0) { - $gateway_fee = round($invoice_amount * $expense_percentage_fee + $expense_flat_fee, 2); - mysqli_query($mysqli,"INSERT INTO expenses SET expense_date = '$pi_date', expense_amount = $gateway_fee, expense_currency_code = '$invoice_currency_code', expense_account_id = $account_id, expense_vendor_id = $expense_vendor_id, expense_client_id = $client_id, expense_category_id = $expense_category_id, expense_description = 'Stripe Transaction for Invoice $invoice_prefix$invoice_number In the Amount of $balance_to_pay', expense_reference = 'Stripe - $pi_id'"); + $stripe_fee = getStripeGatewayFee($payment_intent); + if ($stripe_fee) { + $gateway_fee = floatval($stripe_fee['fee']); + $gateway_fee_currency = escapeSql($stripe_fee['currency']); + mysqli_query($mysqli,"INSERT INTO expenses SET expense_date = '$pi_date', expense_amount = $gateway_fee, expense_currency_code = '$gateway_fee_currency', expense_account_id = $account_id, expense_vendor_id = $expense_vendor_id, expense_client_id = $client_id, expense_category_id = $expense_category_id, expense_description = 'Stripe fee for Invoice $invoice_prefix$invoice_number payment of $balance_to_pay', expense_reference = 'Stripe - $pi_id'"); + } else { + logApp("Stripe", "warning", "Balance transaction unavailable for $pi_id - fee expense not recorded for invoice ID $invoice_id"); + } } // RECEIPT EMAIL diff --git a/functions.php b/functions.php index 5abd11e9..5183cccc 100644 --- a/functions.php +++ b/functions.php @@ -16,3 +16,4 @@ require_once __DIR__ . '/functions/auth.php'; require_once __DIR__ . '/functions/logging.php'; require_once __DIR__ . '/functions/app.php'; require_once __DIR__ . '/functions/db.php'; +require_once __DIR__ . '/functions/payments.php'; diff --git a/functions/payments.php b/functions/payments.php new file mode 100644 index 00000000..55d5ed5f --- /dev/null +++ b/functions/payments.php @@ -0,0 +1,22 @@ + ['latest_charge.balance_transaction']. + * Returns ['fee' => float, 'currency' => 'USD'] or false if unavailable. + */ +function getStripeGatewayFee($payment_intent) +{ + $bt = $payment_intent->latest_charge->balance_transaction ?? null; + + // Not expanded or not yet created (async payment methods) + if (!$bt || is_string($bt)) { + return false; + } + + return [ + 'fee' => round($bt->fee / 100, 2), + 'currency' => strtoupper($bt->currency), + ]; +} \ No newline at end of file diff --git a/guest/guest_pay_invoice_stripe.php b/guest/guest_pay_invoice_stripe.php index 1d26881f..2feb8599 100644 --- a/guest/guest_pay_invoice_stripe.php +++ b/guest/guest_pay_invoice_stripe.php @@ -13,9 +13,6 @@ $stripe_secret = escapeHtml($stripe_provider['payment_provider_private $stripe_account = intval($stripe_provider['payment_provider_account']); $stripe_expense_vendor = intval($stripe_provider['payment_provider_expense_vendor']); $stripe_expense_category = intval($stripe_provider['payment_provider_expense_category']); -$stripe_percentage_fee = floatval($stripe_provider['payment_provider_expense_percentage_fee']); -$stripe_flat_fee = floatval($stripe_provider['payment_provider_expense_flat_fee']); - // Show payment form if (isset($_GET['invoice_id'], $_GET['url_key']) && !isset($_GET['payment_intent'])) { @@ -164,7 +161,10 @@ if (isset($_GET['invoice_id'], $_GET['url_key']) && !isset($_GET['payment_intent require_once '../libs/stripe-php/init.php'; \Stripe\Stripe::setApiKey($stripe_secret); - $pi_obj = \Stripe\PaymentIntent::retrieve($pi_id); + $pi_obj = \Stripe\PaymentIntent::retrieve([ + 'id' => $pi_id, + 'expand' => ['latest_charge.balance_transaction'], + ]); if ($pi_obj->client_secret !== $pi_cs) { error_log("Stripe payment error - Payment intent ID/Secret mismatch for $pi_id"); @@ -223,10 +223,16 @@ if (isset($_GET['invoice_id'], $_GET['url_key']) && !isset($_GET['payment_intent $amount_paid_previously = floatval(mysqli_fetch_assoc($sql_amount_paid_previously)['amount_paid']); $balance_to_pay = $invoice_amount - $amount_paid_previously; - // Stripe expense + // Stripe expense (actual fee from balance transaction) if ($stripe_expense_vendor > 0 && $stripe_expense_category > 0) { - $gateway_fee = round($balance_to_pay * $stripe_percentage_fee + $stripe_flat_fee, 2); - mysqli_query($mysqli, "INSERT INTO expenses SET expense_date = '$pi_date', expense_amount = $gateway_fee, expense_currency_code = '$invoice_currency_code', expense_account_id = $stripe_account, expense_vendor_id = $stripe_expense_vendor, expense_client_id = $client_id, expense_category_id = $stripe_expense_category, expense_description = 'Stripe Transaction for Invoice $invoice_prefix$invoice_number In the Amount of $balance_to_pay', expense_reference = 'Stripe - $pi_id'"); + $stripe_fee = getStripeGatewayFee($pi_obj); + if ($stripe_fee) { + $gateway_fee = floatval($stripe_fee['fee']); + $gateway_fee_currency = escapeSql($stripe_fee['currency']); + mysqli_query($mysqli, "INSERT INTO expenses SET expense_date = '$pi_date', expense_amount = $gateway_fee, expense_currency_code = '$gateway_fee_currency', expense_account_id = $stripe_account, expense_vendor_id = $stripe_expense_vendor, expense_client_id = $client_id, expense_category_id = $stripe_expense_category, expense_description = 'Stripe fee for Invoice $invoice_prefix$invoice_number payment of $balance_to_pay', expense_reference = 'Stripe - $pi_id'"); + } else { + error_log("Stripe payment warning - balance transaction unavailable for $pi_id, fee expense not recorded"); + } } if (intval($balance_to_pay) !== intval($pi_amount_paid)) {