Renewed Without Paying: Billing Moved Expiry Dates on Invoicing
An expiry date that moves when an invoice is issued does not tell you who paid. It only tells you how many times cron has run. This article explains how I found this bug in old code and moved the renewal logic behind a single point where a person confirms receipt of payment.
1-minute summary
- Symptom / problem
- A billing system advanced next_due_date when the invoice was issued, so unpaid customers were renewed, while the slip confirm buttons in three places did not renew
- Who should read
- People building or maintaining recurring service billing
- Fix in short
- Collapse to a single confirmation path that locks the row, records the real amount, closes the invoice when fully paid, renews once per item period, and find customers who were renewed without paying.
I was reading the code of an old billing system that I was about to replace with a Laravel app I had written, checking how its renewal logic worked before migrating things over. Then I found something that made me put my coffee down: the old system advanced a service's expiry date when it issued an invoice, rather than when it received payment. That meant a customer who had not paid a single baht automatically got another service period.
I use only "the old billing system" in this article. I am not comparing brands or identifying the business, because the lesson is in the placement of a single line of code, rather than which software it was, and I have changed all the numbers and names.
The first bug: renewal on invoicing, rather than payment
The system had a scheduled job with a name along the lines of GenerateRecurringInvoices, responsible for issuing invoices in advance. The problem was that the same loop also advanced the service's next_due_date by one period as it created the invoice ahead of time. The sequence looked like this.
As a result, customers who did not pay were not cut off until someone on the team noticed the overdue invoice and manually disabled their service. In a hosting business where customers pay by bank transfer and send a transfer slip, that means the expiry date in the system tells you nothing about the money actually received. It only tells you how many times cron has run.
Personally, I consider this the most dangerous kind of billing bug because it never throws an error or produces a red log entry. Everything looks normal, with a nice future expiry date displayed for every account.
Slip confirmation buttons in three places that renewed nothing
Once I knew cron was advancing the dates, I went back to see what the system did when a customer actually paid. Since cron had already advanced the date, there would presumably be nothing more to do on payment. I found "Confirm slip" buttons in three places: two admin pages with duplicate implementations in separate files, and an API for the chatbot to call when someone confirmed from a phone. All three did the same thing: set the invoice status to paid and stop. None of them called any renewal logic.
I found two other things in the same pass.
- Domain orders did not create a domain row at all, so there was no expiry date to send reminders about.
- The admin invoice form allowed the status to be manually changed to paid, bypassing everything that should happen when payment is received.
When I saw that none of the three buttons renewed anything, I assumed there must be another scheduled job that swept up paid invoices and renewed them later. I searched and found none. The only job that could advance the date was the one issuing invoices. That is why the old system had appeared to work for years despite its logic being back to front.

Six rules I wrote before touching the code
I did not start by fixing a single line, because the problem was that the system's definition of "renewal" was wrong from the beginning. I documented the rules first, then made the code follow them. These six rules formed the core of the work.
- A service can advance only when a person confirms receipt of payment. Issuing an invoice advances nothing.
- An invoice is paid only when the sum of successful payments covers its total. An underpayment leaves it outstanding and does not trigger renewal. A second slip covering the remainder can close the invoice.
- Each invoice item stores
period_startperiod_endperiod_monthsfor the period it pays for. Hosting is renewed throughperiod_endonce per item, thenrenewed_atis set to prevent repetition. - Domains live in a separate table with their own expiry dates, and
expires_atis the registrar's date, which can change only when the registrar confirms it. A paid domain item only setspending_actionto registration or renewal. - Hosting and domains are invoiced different configured numbers of days in advance, with payment due on the expiry date and no duplicate invoices for the same period. If both expire on the same day, they are combined into one invoice and one email. The reminder schedule is configurable.
- An invoice must not be manually set to paid in the edit form. It must go through payment recording so that the renewal step runs every time.
The third rule is my favorite because it removes the guesswork from "what does this invoice pay for, and until when?" If a customer pays for a year of hosting, that period is right there on the line item. There is no need to calculate backward from the invoice date.
The invoice item table with the added period columns looks roughly like this.
ALTER TABLE invoice_items
ADD COLUMN period_start DATE NULL,
ADD COLUMN period_end DATE NULL,
ADD COLUMN period_months TINYINT UNSIGNED NULL,
ADD COLUMN renewed_at TIMESTAMP NULL; -- NULL = ยังไม่ได้ต่ออายุ
-- รายการที่จ่ายแล้วแต่ยังไม่ต่ออายุ ใช้ไล่ตรวจย้อนหลัง
SELECT i.id, ii.id AS item_id, ii.period_end
FROM invoices i
JOIN invoice_items ii ON ii.invoice_id = i.id
WHERE i.status = 'paid' AND ii.renewed_at IS NULL;
One confirmation path: PaymentConfirmation
I consolidated the three places that had handled the same task differently into one class called PaymentConfirmation. Both the admin pages and the chatbot API call the same method. Inside, it always does the same things: lock the rows, record the actual amount received, close the invoice if fully paid, then call the renewal logic.
The slip row needs locking because two people might confirm it at the same time, one from chat and another from the panel. Without lockForUpdate, that would create two payment rows for one slip. This is the same issue I covered in gapless document numbering, using the same kind of lock. For more on preventing duplicate work, the article on atomic job claiming explains the same principle in another context.
public function confirm(PaymentSlip $slip, int $amountSatang, string $confirmedBy, ?string $note, string $source): array
{
$result = DB::transaction(function () use ($slip, $amountSatang, $confirmedBy, $note) {
$locked = PaymentSlip::query()->lockForUpdate()->findOrFail($slip->id);
if ($locked->status !== 'pending') {
return ['ok' => false, 'error' => 'slip_not_pending'];
}
$invoice = Invoice::query()->lockForUpdate()->find($locked->invoice_id);
if (in_array($invoice->status, ['cancelled', 'refunded'], true)) {
return ['ok' => false, 'error' => 'invoice_'.$invoice->status];
}
// ยอดต้องเป็นบวก และไม่เกินยอดค้าง + ส่วนกันพิมพ์ผิดเล็กน้อย (ตั้งใน config)
if (! $this->amountAllowed($invoice, $amountSatang)) {
return ['ok' => false, 'error' => 'amount_out_of_range'];
}
$locked->update(['status' => 'confirmed', 'amount_confirmed' => $amountSatang]);
$paid = $this->recordPayment($invoice, [
'gateway' => 'bank_transfer',
'amount' => $amountSatang,
'txn_id' => 'slip-'.$locked->id,
]);
return ['ok' => true, 'invoice_id' => $invoice->id, 'invoice_paid' => $paid['invoice_paid']];
});
if (! $result['ok']) {
return $result;
}
// ต่ออายุ "หลัง commit" เสมอ และเรียกได้เฉพาะเมื่อใบเป็น paid
$result['actions'] = $this->renewals->applyPaidInvoice(Invoice::find($result['invoice_id']));
return $result;
}
Notice that all money is in satang, stored as integers with no decimals to round incorrectly. An invoice can become paid only when the sum of payments with status = success is greater than or equal to the invoice total. I do not use a paid slip verification API. I deliberately require a person to confirm, because what I need to prevent is renewal without anyone taking responsibility, which was exactly the cause of the first bug.
RenewalService: renew each item for its specified period
Renewal works per item, rather than per invoice. One invoice can contain a hosting item and a domain item. Each must follow a different path, and each must be processed only once even if called repeatedly.
foreach ($invoice->items()->whereNull('renewed_at')->pluck('id') as $itemId) {
DB::transaction(function () use ($itemId, $invoice) {
$item = InvoiceItem::query()->lockForUpdate()->find($itemId);
if (! $item || $item->renewed_at !== null) {
return; // มีคนทำไปแล้ว ข้ามเงียบๆ
}
if ($item->subscription_id) {
$sub = Subscription::query()->lockForUpdate()->find($item->subscription_id);
$target = Carbon::parse($item->period_end);
// โฮสติ้งใหม่ที่ยังไม่เคยเปิด เริ่มนับจากวันที่จ่าย ไม่ใช่วันสั่งซื้อ
if ($sub->status === 'pending' && $item->period_months) {
$target = Carbon::today()->addMonths((int) $item->period_months);
}
if ($target->greaterThan(Carbon::parse($sub->next_due_date))) {
$sub->update(['next_due_date' => $target]); // ขยับไปข้างหน้าอย่างเดียว
}
} elseif ($item->domain_id) {
// วันหมดอายุของโดเมนเป็นของ registrar ไม่แตะที่นี่ แค่ตั้งคิวงาน
Domain::query()->lockForUpdate()->find($item->domain_id)
->update(['pending_action' => 'renew', 'pending_invoice_id' => $invoice->id]);
}
$item->update(['renewed_at' => now()]);
});
}
I took particular care with two points. The first is the greaterThan condition: renewal can move the date forward but never backward. A repeated call or an old invoice appearing later will not move the expiry date back. The second is legacy items created before the period columns existed, which have no period_end. I have those report "manual review required" instead of adding another period, because the old cron has already advanced their dates. Adding another would renew them twice.
Renew on invoicing
cron advances next_due_date as soon as an invoice is created. Slip confirmation only changes the status. Customers get renewed without paying.
Renew when a person confirms payment
The only path is PaymentConfirmation, which then calls RenewalService for each item's specified period, once per item.
I deliberately separated domains because registering or renewing a domain spends real money with the registrar. If the system did that automatically as soon as a customer transferred money, and one fake slip slipped through, I would be paying out of my own pocket. The system therefore only sets pending_action for a person to carry out the action at the registrar, and the domain's expiry date changes only when the registrar confirms it.

Other bugs I found while reading
While tracing the code, I found three more issues that were not directly related to renewal but also silently distorted the numbers.
config/app.phphardcoded the timezone to UTC without readingAPP_TIMEZONE, so "today" in cron meant the UTC date, and customers' transfer times were stored in UTC. I changed it to Asia/Bangkok, but old production rows had already been written in UTC. Changing the config does not fix them retroactively.- Five customer pages displayed satang as baht, making the numbers a hundred times too large.
- The payment page read invoice item fields that did not exist.
// config/app.php
'timezone' => env('APP_TIMEZONE', 'Asia/Bangkok'),
I want to stress the timezone issue because people often think changing one setting finishes the job. If the database contains timestamps written in UTC, those rows remain in UTC. You need to know which rows were written before the change so that historical reports do not leave you wondering why an invoice paid in the early morning appears on a different day.
Finding customers who had already been renewed without paying
After fixing the code, there was still the question of who had received free renewals "up to now." I kept that question separate from the code fix, because cutting off a customer's service is a decision for a person, rather than a script. I only wrote a query to list the records and passed it to the person responsible to decide whether to chase payment or let it go.
-- บริการที่วันหมดอายุอยู่ในอนาคต แต่ไม่มีใบที่จ่ายแล้วครอบคลุมช่วงนั้น
SELECT s.id, s.next_due_date
FROM subscriptions s
WHERE s.next_due_date > CURDATE()
AND NOT EXISTS (
SELECT 1
FROM invoice_items ii
JOIN invoices i ON i.id = ii.invoice_id AND i.status = 'paid'
WHERE ii.subscription_id = s.id
AND ii.period_end >= s.next_due_date
);
This query works only for items that already have the period columns. Older items have no period_end, so they will all appear even if some were fully paid. I therefore treat the result as a list for people to review, rather than a list of unpaid customers. This is the same reason the renewal logic refuses to guess a period for items without that data.
Add a daily check that reports paid invoices with items whose renewed_at is still empty. If any rows appear, it means another shortcut is changing invoice status without going through PaymentConfirmation, which is the same kind of bug I found at the start.
Testing that money does not renew services by itself
I wrote tests covering the exact points where the bugs had been. There were 29 after phases A through E, and 43 in the final code. The test base class refuses to run unless the database name ends in _test, to prevent accidentally running against real data. I also used a fake chatbot to call the slip confirmation API and test the actual integration.
# เทสต์ที่เกี่ยวกับเรื่องนี้โดยตรง
php artisan test --filter=PaymentConfirmationTest
php artisan test --filter=RenewalServiceTest
# ผลที่ต้องได้: ออกใบเฉยๆ ไม่ขยับวัน / โอนขาดไม่ต่อ / กดยืนยันซ้ำได้ payment เดียว
The rules in this article belong to one small hosting business, including having people confirm slips manually and allowing customers to make partial payments in installments. Yours may need a grace policy or a payment gateway that confirms payments automatically. For money, tax, and tax invoices, always consult someone with accounting expertise first.
To put it as briefly as I can, I do not think this is about Laravel or any particular billing system. It comes down to one question I should ask whenever I encounter renewal code: "Is the line that advances the expiry date called after the money arrives, or before?" If the answer is before, or I do not know, I should assume there are already customers using the service without paying. Feel free to replace the direct call with a queue or event, as long as there is one place responsible for this. I will come back and add more fixes later.
Want us to set this up?
Get help with server setup, configuration, migration, or troubleshooting. Save time for the work that matters.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first