Lesson 80: Preventing Duplicate Auctions for the Same Listing with Database-Level Validation

Introduction

As the Flipnzee Auctions plugin continued to mature, most of the auction workflow had become stable. Earlier lessons introduced automatic auction closing, winner detection, transaction generation, payment management, and duplicate transaction protection.

While reviewing historical auction data, another important question arose:

Can a listing accidentally have more than one active auction?

Although previous improvements had already reduced the possibility of duplicate auctions, adding another layer of protection inside the Auction Manager would make the plugin even more reliable.

This lesson focuses on auditing the auction creation workflow and implementing a final database-level safeguard that prevents multiple active auctions from being created for the same listing.


Why This Improvement Matters

A marketplace should never allow confusion about which auction is currently valid.

Without proper validation, multiple active auctions for the same listing could cause:

  • Multiple bidding interfaces
  • Conflicting highest bids
  • Incorrect winner selection
  • Duplicate transactions
  • Difficult ownership transfer

Even if such situations only occur because of programming mistakes or repeated requests, preventing them is essential.


Current Workflow Review

Before making changes, the existing auction lifecycle should be reviewed.

Listing Created
        │
        ▼
Create Auction
        │
        ▼
Auction Starts
        │
        ▼
Users Place Bids
        │
        ▼
Auction Ends
        │
        ▼
Winner Selected
        │
        ▼
Transaction Created

The only missing safeguard is ensuring that only one active auction can exist for a listing at any given time.


Objectives

In this lesson we will:

  • Audit the auction creation logic.
  • Search where auctions are inserted into the database.
  • Check whether an active auction already exists.
  • Prevent duplicate active auctions.
  • Return the existing auction instead of creating another one.
  • Test the protection with multiple creation attempts.

Implementation Plan

Step 1

Locate the auction creation method.

Search for:

create_auction(

or

$wpdb->insert(

inside

includes/class-auction-manager.php

Step 2

Before inserting a new auction, search for an existing active auction belonging to the same listing.

The validation should resemble:

SELECT id
FROM wp_flipnzee_auctions
WHERE listing_id = ?
AND status = 'active'
LIMIT 1

Step 3

If an active auction exists:

  • do not insert another record
  • return the existing auction ID

Step 4

Only if no active auction exists should the plugin execute:

$wpdb->insert(...)

Step 5

Test using:

  • Add Auction page
  • Edit Auction page
  • phpMyAdmin
  • Frontend listing page

Expected Workflow After Improvement

Create Auction
        │
        ▼
Check Active Auction
        │
   Exists?
    │       │
   Yes      No
    │        │
Return ID  Create Auction

What We Will Learn

This lesson introduces another important software engineering principle:

  • Defensive programming
  • Database validation
  • Idempotent creation methods
  • Marketplace integrity
  • Multi-layer validation
  • Business rule enforcement

Files Expected to Change

Primary file:

includes/class-auction-manager.php

Possible testing files:

admin/class-admin-add-auction.php

admin/class-admin-edit-auction.php

Expected Outcome

After completing Lesson 80:

  • A listing can never have two active auctions.
  • Duplicate auction creation attempts become harmless.
  • Historical auction records remain preserved.
  • Marketplace integrity improves.
  • The auction lifecycle becomes even more robust.

Difficulty

Intermediate


Estimated Time

30–45 minutes


Next Lesson Preview

Lesson 81 – Automatically Archive Completed Auctions and Preserve Historical Records

We’ll enhance the auction lifecycle by introducing an archival mechanism so completed auctions are retained for reporting and auditing while keeping active auction data clean and efficient.

Lesson 79: Auditing and Hardening the Transaction Creation Lifecycle in the Flipnzee Auctions Plugin

After successfully implementing the Payment Management system in the previous lessons, the next objective was to review the entire transaction creation workflow. During testing, some historical records revealed duplicate transactions for the same auction. Although these duplicates originated from earlier development versions of the plugin, this lesson focused on ensuring that such duplicates could never occur again.

Instead of simply assuming the issue had been resolved, the transaction creation logic was audited and strengthened by adding a final database validation before inserting a new transaction.


What We Wanted to Achieve

The transaction system should always follow these rules:

  • A listing can have multiple auctions over time.
  • Every auction should have only one winner.
  • Every auction should generate only one transaction.
  • Repeated callbacks or cron executions must never create duplicate transaction records.

Investigating the Transaction Lifecycle

The first step was to locate where transactions were actually inserted into the database.

Using Visual Studio Code’s global search, all $wpdb->insert() calls were reviewed.

Several insert operations were found:

  • Auction creation
  • Bid creation
  • Transaction creation

The transaction insertion code was located inside:

includes/class-transaction-manager.php

The original code directly inserted a new transaction without checking whether one already existed for the same auction.

$result = $wpdb->insert(
    $table,
    array(
        'auction_id'  => $data['auction_id'],
        'listing_id'  => $data['listing_id'],
        'seller_id'   => $data['seller_id'],
        'buyer_id'    => $data['buyer_id'],
        'winning_bid' => $data['winning_bid'],
        'status'      => 'pending',
    ),
    array(
        '%d',
        '%d',
        '%d',
        '%d',
        '%f',
        '%s',
    )
);

Although this worked correctly, it would create duplicate records if the function were accidentally executed more than once.


Adding Duplicate Transaction Protection

Before performing the insert operation, a database lookup was added.

The plugin now searches for an existing transaction belonging to the current auction.

$existing_transaction = $wpdb->get_var(
    $wpdb->prepare(
        "SELECT id
         FROM {$table}
         WHERE auction_id = %d
         LIMIT 1",
        absint( $data['auction_id'] )
    )
);

if ( $existing_transaction ) {
    return (int) $existing_transaction;
}

Only when no transaction exists does the plugin continue with the insert.

This small addition makes the transaction creation process significantly more reliable.


Why This Matters

Imagine the following sequence:

Auction Ends
        │
        ▼
Winner Determined
        │
        ▼
Create Transaction

If the creation function is accidentally triggered twice—for example by a scheduled task or callback—the previous implementation would create two database records.

With the new validation:

Auction Ends
        │
        ▼
Winner Determined
        │
        ▼
Check Existing Transaction
        │
   Exists?
    │     │
   Yes    No
    │      │
Return ID  Insert Transaction

Only one transaction can ever be created for the same auction.


Understanding Idempotent Operations

One of the most important concepts introduced in this lesson is idempotency.

An idempotent function produces the same result no matter how many times it is executed.

For example:

First execution
↓

Transaction Created

Second execution
↓

Existing transaction found

↓

No duplicate inserted

This principle is widely used in payment gateways, webhooks, APIs, and marketplace systems to prevent duplicate records.


Testing the Implementation

After updating the code:

  • The plugin was validated using PHP syntax checking.
  • A fresh auction was created.
  • The auction was allowed to end automatically.
  • A winning bidder was determined.
  • The transaction was created.
  • Payment status was updated.
  • The Transactions page was reviewed.
  • phpMyAdmin was used to verify the database.

The results confirmed:

  • Only one transaction was created.
  • Payment updates continued to function correctly.
  • No duplicate transaction records appeared.
  • The transaction lifecycle remained fully functional.

Final Transaction Lifecycle

After this improvement, the workflow became:

Create Auction
        │
        ▼
Place Bids
        │
        ▼
Auction Ends
        │
        ▼
Winner Determined
        │
        ▼
Check Existing Transaction
        │
        ▼
Create One Transaction
        │
        ▼
Payment Processing

This provides a much more robust and production-ready transaction system.


Lessons Learned

Several valuable software engineering concepts were reinforced during this implementation:

  • Always audit historical issues instead of assuming they are resolved.
  • Database validation is an effective safeguard against duplicate records.
  • Critical workflows should be idempotent whenever possible.
  • Defensive programming increases reliability in real-world applications.
  • Marketplace and escrow systems benefit greatly from multiple layers of validation.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Conclusion

Lesson 79 focused on strengthening the transaction creation process rather than introducing new functionality. By adding a simple database existence check before inserting a transaction, the plugin now guarantees that each auction can generate only one transaction, even if the creation routine is triggered multiple times.

This enhancement makes the Flipnzee Auctions plugin more resilient and establishes a solid foundation for the upcoming escrow and ownership transfer workflow in future lessons.

Lesson 79: Auditing and Fixing the Auction Transaction Creation Lifecycle

After successfully implementing manual payment status management in Lesson 78, we noticed an unexpected behavior during testing.

Although payment management was working perfectly, new transactions were being created before an auction had actually finished. This indicated a flaw in the auction workflow rather than in the payment management system.

Before integrating Escrow.com or any payment gateway, it is essential that every auction follows a predictable lifecycle and creates only one transaction, at the correct point in the auction process.

In this lesson, we will audit the entire transaction creation workflow and ensure that transactions are generated only after an auction closes and a winner has been determined.


What We Will Build

By the end of this lesson we will:

  • Trace where transactions are created.
  • Identify every function capable of creating a transaction.
  • Prevent duplicate transaction creation.
  • Ensure transactions are created only once.
  • Verify the transaction lifecycle from auction creation to payment.

The Problem We Discovered

During testing we observed several unexpected behaviors.

  • Transactions were sometimes created immediately after an auction was created.
  • Earlier testing produced duplicate transaction records.
  • Payment management worked correctly, but the transaction lifecycle itself was inconsistent.

Although these issues were corrected temporarily during testing, the underlying workflow still needs a proper audit.


Desired Auction Workflow

A professional auction platform should always follow this sequence.

Auction Created
        │
        ▼
Accept Bids
        │
        ▼
Auction Ends
        │
        ▼
Determine Winner
        │
        ▼
Create ONE Transaction
        │
        ▼
Pending Payment
        │
        ▼
Buyer Payment Submitted
        │
        ▼
Admin Verification
        │
        ▼
Payment Approved
        │
        ▼
Escrow Started
        │
        ▼
Ownership Transfer
        │
        ▼
Auction Completed

Every completed auction should generate exactly one transaction, and that transaction should remain the single source of truth throughout the payment and ownership transfer process.


Lesson Objectives

During this lesson we will:

Step 1

Search the entire plugin for every location that inserts records into:

wp_flipnzee_transactions

Step 2

Identify every function responsible for transaction creation.

Possible examples include:

  • winner determination
  • auction closing
  • bid completion
  • scheduled cron events
  • save handlers

Step 3

Determine which function should have exclusive responsibility for creating transactions.


Step 4

Prevent duplicate transaction creation by checking whether a transaction already exists before inserting a new record.


Step 5

Verify that transaction creation occurs only after:

  • auction end time
  • winner determination
  • successful auction closure

Step 6

Perform end-to-end testing by:

  • creating a new auction
  • placing bids
  • waiting for auction completion
  • confirming exactly one transaction is created

Expected Outcome

After completing this lesson:

  • Every auction will produce only one transaction.
  • Duplicate transactions will be impossible.
  • Transactions will be created only after auction completion.
  • The plugin will have a reliable transaction lifecycle ready for payment gateway and Escrow.com integration.

Why This Matters

Payment gateways, escrow providers, and ownership transfer systems all depend on having a single, reliable transaction record.

Fixing the transaction lifecycle now will make future features significantly easier to implement and reduce the likelihood of data inconsistencies.

This lesson focuses on strengthening the core architecture of the Flipnzee Auctions plugin before moving on to advanced payment and escrow functionality.

Lesson 78: Building Payment Status Management for Auction Transactions in the Flipnzee Plugin

In the previous lesson, we built the Transaction Details page to display complete information about a transaction. While administrators could view payment information, there was no way to manage the payment lifecycle from the WordPress dashboard.

In this lesson, we implemented a complete Payment Status Management system. Administrators can now update the payment status directly from the Transaction Details page, with all changes securely stored in the database.


What We Built

The Transaction Details page now includes a dedicated Payment Management section that allows administrators to:

  • View the current payment status
  • Select a new payment status
  • Save the updated status
  • Automatically update the transaction timestamp
  • Reload the page showing the updated information

Supported payment statuses include:

  • Pending
  • Processing
  • Paid
  • Completed
  • Cancelled
  • Refunded

Step 1: Creating the Payment Management Section

Below the transaction information table, a new section was added.

<h2><?php esc_html_e( 'Payment Management', 'flipnzee-auctions' ); ?></h2>

<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">

This form submits data securely using WordPress’ admin-post handler.


Step 2: Adding WordPress Security

To protect the form against CSRF attacks, a nonce field was added.

wp_nonce_field(
    'flipnzee_update_payment_status',
    'flipnzee_payment_nonce'
);

Every request is now verified before any database update occurs.


Step 3: Passing Required Hidden Values

Hidden fields tell WordPress which handler to execute and which transaction should be updated.

<input
    type="hidden"
    name="action"
    value="flipnzee_update_transaction_status">

<input
    type="hidden"
    name="transaction_id"
    value="<?php echo absint( $transaction->id ); ?>">

Step 4: Building the Payment Status Dropdown

Administrators can now select from predefined payment states.

<select name="payment_status">

<option value="pending">Pending</option>
<option value="processing">Processing</option>
<option value="paid">Paid</option>
<option value="completed">Completed</option>
<option value="cancelled">Cancelled</option>
<option value="refunded">Refunded</option>

</select>

The currently saved status is automatically selected.


Step 5: Adding the Update Button

A standard WordPress button submits the form.

submit_button(
    __( 'Update Payment Status', 'flipnzee-auctions' )
);

Step 6: Registering the Form Handler

Inside the constructor, we registered the admin action.

add_action(
    'admin_post_flipnzee_update_transaction_status',
    array( $this, 'update_payment_status' )
);

This tells WordPress which method should process the form submission.


Step 7: Creating update_payment_status()

A new method was added to process updates.

public function update_payment_status() {

    check_admin_referer(
        'flipnzee_update_payment_status',
        'flipnzee_payment_nonce'
    );

}

The method validates the request before making any database changes.


Step 8: Sanitizing User Input

Incoming values are sanitized before use.

$transaction_id = absint(
    $_POST['transaction_id']
);

$payment_status = sanitize_text_field(
    wp_unslash(
        $_POST['payment_status']
    )
);

Step 9: Updating the Database

The transaction record is updated using the WordPress database API.

$wpdb->update(

    $wpdb->prefix . 'flipnzee_transactions',

    array(

        'payment_status' => $payment_status,

        'updated_at' => current_time( 'mysql' ),

    ),

    array(

        'id' => $transaction_id,

    )

);

Step 10: Redirecting Back to the Transaction

After saving, the administrator is redirected back to the same transaction.

wp_safe_redirect(

    admin_url(

        'admin.php?page=flipnzee-transaction-details&transaction_id='
        . $transaction_id

    )

);

exit;

Problems We Encountered

During implementation we discovered several issues.

PHP Parse Errors

Some HTML blocks were accidentally inserted outside PHP, producing syntax errors.

These were corrected by carefully closing and reopening PHP tags where required.


Missing Transaction ID

Initially the transaction details page displayed:

Transaction not found.

The redirect URL was missing the transaction ID.

Adding:

transaction_id=

to the redirect resolved the issue.


Handler Verification

To confirm the form reached the correct handler, a temporary debug message was added.

die( 'Payment status handler reached.' );

After confirming the handler worked, the debug statement was removed.


Database Verification

Using phpMyAdmin we confirmed that updates correctly modified:

  • payment_status
  • updated_at

while leaving the remaining transaction information unchanged.


Testing Performed

The new payment workflow was tested thoroughly.

✔ Opened Transaction Details page

✔ Changed status from Pending to Completed

✔ Saved successfully

✔ Database updated correctly

✔ Timestamp refreshed automatically

✔ Page redirected back to the same transaction

✔ Updated value displayed correctly

✔ Multiple status changes tested successfully


Final Result

The Flipnzee Auctions plugin now includes a functional payment management system directly inside the WordPress administration panel.

Administrators can securely update payment statuses without editing the database manually, providing a much smoother workflow for managing completed auction transactions.

This feature also lays the groundwork for future integrations with payment gateways and escrow services, where payment states can eventually be synchronized automatically instead of being updated manually.


Source Code Summary

Register Admin Action

add_action(
    'admin_post_flipnzee_update_transaction_status',
    array( $this, 'update_payment_status' )
);

Nonce

wp_nonce_field(
    'flipnzee_update_payment_status',
    'flipnzee_payment_nonce'
);

Update Query

$wpdb->update(

    $wpdb->prefix . 'flipnzee_transactions',

    array(

        'payment_status' => $payment_status,

        'updated_at' => current_time( 'mysql' ),

    ),

    array(

        'id' => $transaction_id,

    )

);

Redirect

wp_safe_redirect(

    admin_url(
        'admin.php?page=flipnzee-transaction-details&transaction_id='
        . $transaction_id
    )

);

exit;

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:

What We Learned

  • Creating secure admin forms using admin-post.php
  • Protecting form submissions with WordPress nonces
  • Sanitizing and validating administrator input
  • Updating custom database tables using $wpdb->update()
  • Redirecting users safely after processing forms
  • Debugging form handlers and URL parameters
  • Verifying database changes using phpMyAdmin
  • Building a maintainable payment workflow for future escrow and payment gateway integration

Lesson 78: Processing Administrator Payment Status Updates and Beginning Payment Verification

Overview

In the previous lesson, a dedicated Administrator Payments Dashboard was introduced, allowing administrators to view submitted buyer payments, inspect transaction details, and access a payment management interface.

However, the interface was still informational. Although administrators could select a payment status from a dropdown, those changes were not yet saved to the database.

In this lesson, we will connect the user interface to the backend by implementing secure form processing and updating payment records.


Objectives

By the end of this lesson, we will:

  • Register a secure administrator POST action.
  • Process payment status update requests.
  • Verify administrator permissions.
  • Validate WordPress nonces.
  • Update the payment_status field in the database.
  • Redirect administrators with success messages.
  • Prepare the payment verification workflow for future approval actions.

Why This Lesson Is Important

Until now, administrators could only view payment information.

This lesson transforms the payment dashboard into a working management system by allowing administrators to update payment progress after reviewing submitted payment proofs.


Current Workflow

Current administrator workflow:

Buyer Uploads Payment Proof
            │
            ▼
Payment Appears in Dashboard
            │
            ▼
Administrator Opens Details
            │
            ▼
Select Payment Status
            │
            ▼
Nothing Happens ❌

Desired Workflow

After this lesson:

Buyer Uploads Payment Proof
            │
            ▼
Payment Appears in Dashboard
            │
            ▼
Administrator Opens Details
            │
            ▼
Select Payment Status
            │
            ▼
Click Update
            │
            ▼
Database Updated
            │
            ▼
Success Message Displayed

Planned Implementation

1. Register the Admin POST Action

The payment management form already submits to WordPress using admin-post.php.

This lesson will register a dedicated action handler for processing payment updates.


2. Verify Administrator Permissions

Before processing any request, the plugin will confirm that the current user has sufficient privileges.

Only administrators should be allowed to modify payment records.


3. Verify the Nonce

Every request will validate the security nonce before updating the database.

This protects against Cross-Site Request Forgery (CSRF) attacks.


4. Validate Submitted Data

Incoming data will be sanitized and validated before use.

Examples include:

  • Transaction ID
  • Payment Status

This ensures only expected values are processed.


5. Update the Database

The selected payment status will be written to the payment_status column of the transaction table.

Typical status transitions include:

  • Pending
  • Processing
  • Paid
  • Completed
  • Cancelled
  • Refunded

6. Redirect Back to the Transaction

After processing, administrators will be redirected back to the Transaction Details page instead of the generic transactions list.

This provides a smoother workflow.


7. Display Success Notices

Administrators should immediately know whether the update succeeded.

Examples include:

Payment status updated successfully.

or

Unable to update payment status.

8. Prepare for Payment Approval

Although this lesson focuses on updating payment statuses, the implementation prepares the foundation for future verification actions.

Upcoming lessons will introduce dedicated buttons such as:

  • Approve Payment
  • Reject Payment
  • Request New Payment Proof

Database Changes

This lesson will primarily update the following transaction field:

payment_status

Possible values include:

  • pending
  • submitted
  • processing
  • paid
  • completed
  • cancelled
  • refunded

Future lessons may introduce additional verification-specific statuses if needed.


Security Considerations

The payment verification process will follow standard WordPress security practices:

  • Capability checks
  • Nonce verification
  • Data sanitization
  • Safe database updates
  • Secure redirects

Expected Outcome

After completing this lesson:

  • Administrators can update payment status.
  • Database records are updated securely.
  • Transaction details immediately reflect the latest payment state.
  • Payment management becomes fully functional.
  • The administrator workflow becomes suitable for production use.

What You Will Learn

During this lesson, you will learn how to:

  • Process administrator forms using admin-post.php.
  • Secure backend form submissions.
  • Update custom database tables.
  • Redirect users after successful processing.
  • Separate payment management from transaction management.

Looking Ahead

Once payment status updates are working, the Flipnzee Auctions plugin will be ready for the next stage of payment verification.


Next Lesson Preview

Lesson 79: Reviewing Uploaded Payment Proofs and Approving Buyer Payments

In the next lesson, we will enhance the administrator experience by allowing payment proofs to be viewed directly from the Transaction Details page. Administrators will be able to inspect uploaded receipts, preview images or PDFs, and approve or reject payments before initiating the website ownership transfer process.

This will bring Flipnzee one step closer to a complete end-to-end marketplace workflow and lay the groundwork for integrating Escrow.com as the preferred payment gateway for live auctions.

Lesson 77 Implementation: Building the Administrator Payment Review Dashboard for Flipnzee Auctions

In the previous lesson, buyers were able to upload payment proof securely through the payment page, with uploaded receipts stored in the WordPress Media Library and linked to the corresponding transaction.

This lesson shifted focus from the buyer to the administrator by introducing a dedicated payment review dashboard. Administrators can now view submitted payments, inspect transaction details, and prepare payments for verification.


Objective

The primary goal of this lesson was to create an administrator interface that allows the Flipnzee team to review buyer payment submissions before approving website ownership transfers.

By the end of this implementation, administrators could:

  • View all submitted payments.
  • Open detailed transaction information.
  • Review payment metadata.
  • Prepare payment status management.
  • Lay the foundation for future payment verification.

Step 1 – Creating the Admin Payments Page

A new administrator page was created.

File created

admin/class-admin-payments.php

The page was implemented as a dedicated admin class.

class Flipnzee_Admin_Payments {

    /**
     * Render Payments page.
     *
     * @return void
     */
    public static function render_page() {

        ?>

        <div class="wrap">

            <h1>Buyer Payments</h1>

            <p>

                Review buyer payment submissions before approving
                the transfer of ownership.

            </p>

        </div>

        <?php
    }
}

This provided a clean starting point for the administrator payment workflow.


Step 2 – Registering the Payments Menu

A new submenu was added beneath the Flipnzee Auctions admin menu.

add_submenu_page(
    'flipnzee-auctions',
    'Payments',
    'Payments',
    'manage_options',
    'flipnzee-payments',
    array(
        'Flipnzee_Admin_Payments',
        'render_page',
    )
);

This created a dedicated Payments section for administrators.


Step 3 – Loading Submitted Payments

The Payments page was connected to the transaction table.

global $wpdb;

$table = $wpdb->prefix . 'flipnzee_transactions';

$payments = $wpdb->get_results(
    "
    SELECT *
    FROM {$table}
    WHERE payment_status = 'submitted'
    ORDER BY updated_at DESC
    "
);

Only transactions that had submitted payment proofs were displayed.


Step 4 – Handling Empty Results

Before rendering the table, the plugin checks whether submitted payments exist.

if ( empty( $payments ) ) {

    echo '<p>No payment submissions found.</p>';

} else {

    // Display payment table.

}

This prevents empty tables and provides useful feedback to administrators.


Step 5 – Building the Payments Table

A professional WordPress admin table was introduced.

<table class="widefat striped">

    <thead>

        <tr>

            <th>ID</th>
            <th>Listing</th>
            <th>Buyer</th>
            <th>Amount</th>
            <th>Gateway</th>
            <th>Status</th>
            <th>Submitted</th>
            <th>Actions</th>

        </tr>

    </thead>

The table closely follows the standard WordPress administration interface.


Step 6 – Displaying Submitted Payments

Each submitted payment is displayed using a loop.

<?php foreach ( $payments as $payment ) : ?>

<tr>

    <td><?php echo esc_html( $payment->id ); ?></td>

    <td><?php echo esc_html( $payment->listing_id ); ?></td>

    <td><?php echo esc_html( $payment->buyer_id ); ?></td>

    <td><?php echo esc_html(
        number_format_i18n(
            $payment->winning_bid,
            2
        )
    ); ?></td>

    <td><?php echo esc_html(
        $payment->payment_gateway
    ); ?></td>

    <td><?php echo esc_html(
        ucfirst( $payment->payment_status )
    ); ?></td>

    <td><?php echo esc_html(
        $payment->updated_at
    ); ?></td>

</tr>

<?php endforeach; ?>

The administrator can immediately identify submitted payments requiring review.


Step 7 – Adding the View Details Button

Instead of displaying placeholder text, each payment now links to a detailed transaction page.

<td>

    <a
        class="button button-primary"
        href="<?php echo esc_url(
            admin_url(
                'admin.php?page=flipnzee-transaction-details&transaction_id=' .
                absint( $payment->id )
            )
        ); ?>">

        View Details

    </a>

</td>

This significantly improves navigation between the payment dashboard and transaction details.


Step 8 – Enhancing the Transaction Details Page

The existing transaction details page was expanded with payment information.

Additional rows were added to display:

<tr>
    <th>Payment Status</th>
    <td><?php echo esc_html(
        ucfirst( $transaction['payment_status'] )
    ); ?></td>
</tr>

<tr>
    <th>Payment Gateway</th>
    <td><?php echo esc_html(
        $transaction['payment_gateway']
    ); ?></td>
</tr>

<tr>
    <th>Payment Submitted</th>
    <td><?php echo esc_html(
        $transaction['payment_submitted_at']
    ); ?></td>
</tr>

Administrators can now review payment-specific information alongside the transaction details.


Step 9 – Creating the Payment Management Section

A dedicated Payment Management panel was introduced.

<h2>Payment Management</h2>

<form
    method="post"
    action="<?php echo esc_url(
        admin_url( 'admin-post.php' )
    ); ?>">

This prepares the interface for future payment verification actions.


Step 10 – Securing the Form

The management form was protected using a WordPress nonce.

wp_nonce_field(
    'flipnzee_update_payment_status',
    'flipnzee_payment_nonce'
);

This ensures only legitimate administrators can submit payment updates.


Step 11 – Payment Status Dropdown

Administrators can now select a payment status.

<select
    name="payment_status"
    id="payment_status">

    <option value="pending">Pending</option>

    <option value="processing">Processing</option>

    <option value="paid">Paid</option>

    <option value="completed">Completed</option>

    <option value="cancelled">Cancelled</option>

    <option value="refunded">Refunded</option>

</select>

Although the update handler will be implemented in the next lesson, the interface is now fully prepared.


Challenges Encountered

Several issues arose during development.

Method Name Mismatch

Initially, the Payments submenu referenced render_page(), while the class still used render().

Standardizing on render_page() resolved the fatal error.


PHP and HTML Mixing

While building the Payment Management form, HTML was accidentally placed inside an open PHP block.

Example:

<?php

wp_nonce_field(...);

<input ...>

Closing PHP before the HTML resolved the syntax error.


Duplicate Status Rows

During iterative development, duplicate Payment Status rows were unintentionally introduced.

Cleaning up duplicate markup produced a clearer transaction details page.


Payment vs Transaction Status

One important architectural decision emerged during development.

The plugin now distinguishes between:

  • status (overall transaction lifecycle)
  • payment_status (buyer payment lifecycle)

This separation prepares the plugin for multiple payment gateways, including Escrow.com, without affecting the broader transaction workflow.


Testing Performed

The implementation was tested by:

  • Opening the new Payments admin menu.
  • Confirming submitted transactions appear in the table.
  • Verifying payment amounts and gateways display correctly.
  • Opening transaction details using the View Details button.
  • Confirming payment metadata is displayed.
  • Checking the Payment Management form renders correctly.
  • Validating PHP syntax after each modification.

Lessons Learned

This implementation reinforced several WordPress development practices:

  • Separate administrator workflows from buyer workflows.
  • Keep transaction management and payment management independent.
  • Use dedicated admin pages instead of overloading existing screens.
  • Secure administrator forms using nonces.
  • Build reusable interfaces that can support additional payment gateways in future.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Current Progress

At the end of Lesson 77, the Flipnzee Auctions plugin now includes:

  • ✅ Administrator Payments menu
  • ✅ Submitted Payments dashboard
  • ✅ Payment listing table
  • ✅ View Details navigation
  • ✅ Enhanced transaction details page
  • ✅ Payment metadata display
  • ✅ Payment Management interface
  • ✅ Secure administrator form ready for processing

The actual processing of payment status updates will be completed in the next lesson.


Next Lesson

Lesson 78: Processing Administrator Payment Status Updates

In the next lesson, we will connect the Payment Management form to the backend by:

  • Registering the administrator POST handler.
  • Verifying administrator permissions and nonces.
  • Updating the payment_status field in the database.
  • Redirecting administrators with success messages.
  • Preparing the workflow for payment approval, rejection, and future Escrow.com integration.

This will complete the first functional administrator payment verification workflow in the Flipnzee Auctions plugin.

Lesson 72: Building the Payment Gateway Selection Interface

Objective

With the payment architecture now prepared, the next logical step is to give buyers the ability to choose how they would like to pay.

In this lesson, we will introduce a Payment Method Selection section on the Payment page. Although only a placeholder gateway exists today, the interface will be built so future gateways (Stripe, PayPal, Razorpay, Bank Transfer, Crypto, etc.) can be added with almost no changes to the frontend.

This lesson focuses entirely on UI architecture, not actual payment processing.


What We’ll Build

Instead of only showing:

Payment Gateway
Manual Payment (Coming Soon)

the payment page will display something like:

Select Payment Method

(•) Manual Payment (Coming Soon)
( ) Stripe
( ) PayPal
( ) Razorpay
( ) Cryptocurrency (USDT)

[Continue]

Only Manual Payment will be enabled.

The remaining gateways will appear disabled with a “Coming Soon” label.


Why This Lesson Matters

This is an important architectural step because:

  • separates payment UI from payment logic
  • allows new gateways without redesigning pages
  • provides a familiar checkout experience
  • keeps the plugin scalable
  • prepares for future gateway plugins

Files We’ll Modify

Existing

includes/class-payment-page.php

Existing

includes/class-payment-manager.php

(add helper function for available gateways)


New Features

1. Payment Gateway List

Create a helper such as:

Flipnzee_Payment_Manager::get_available_gateways()

which returns an array like

array(
    'manual' => array(
        'label' => 'Manual Payment',
        'enabled' => true,
    ),
    'stripe' => array(
        'label' => 'Stripe',
        'enabled' => false,
    ),
    'paypal' => array(
        'label' => 'PayPal',
        'enabled' => false,
    ),
    'razorpay' => array(
        'label' => 'Razorpay',
        'enabled' => false,
    ),
    'crypto' => array(
        'label' => 'USDT Cryptocurrency',
        'enabled' => false,
    ),
);

2. Display Gateway Choices

Show all gateways as radio buttons.

Only enabled gateways are selectable.

Disabled gateways display:

Coming Soon

3. Continue Button

Display

Continue to Payment

No payment processing yet.


4. Clean HTML Structure

Wrap the section in

<div class="flipnzee-payment-gateways">

for future styling.


User Experience

Current page:

Transaction Details

Gateway:
Manual Payment

New page:

Transaction Details

Select Payment Method

○ Stripe
○ PayPal
● Manual Payment
○ Razorpay
○ Crypto

Continue

Benefits

After this lesson the plugin will have:

  • scalable payment architecture
  • configurable gateway list
  • reusable gateway rendering
  • future-ready checkout interface
  • no dependency on a specific payment provider

What We Won’t Build Yet

To keep the project stable, we are not implementing:

  • Stripe API
  • PayPal API
  • Razorpay API
  • Crypto payments
  • Order confirmation
  • Payment verification

Those will come in later lessons.


Expected Outcome

By the end of Lesson 72, buyers will see a professional payment method selection interface with a working placeholder for Manual Payment and clearly marked future payment options, laying the foundation for integrating real payment gateways in the upcoming lessons.

Lesson 73: Capturing and Validating the Buyer’s Selected Payment Method

Objective

In the previous lesson, we introduced a dynamic payment gateway selection interface. Buyers can now see the available payment methods, but their selection is not yet processed.

In this lesson, we’ll begin building the actual checkout workflow by wrapping the gateway list inside a form, capturing the selected payment method, validating it on submission, and preparing the plugin for gateway-specific payment processing.

Although real payment gateways are still not connected, this lesson establishes the core workflow that every future payment provider will use.


Why This Lesson Matters

A payment page is only useful if it can process the buyer’s choice.

Instead of immediately integrating Stripe, PayPal, or Escrow.com APIs, we first need a common checkout workflow that:

  • accepts the selected gateway
  • validates user input
  • prevents invalid gateway selections
  • prepares the transaction for payment
  • redirects to the appropriate payment handler

Once this workflow exists, every new payment provider can plug into it.


What We’ll Build

The payment page will evolve from:

○ Escrow.com
● Manual Payment
○ Stripe
○ PayPal

[Continue (Disabled)]

into:

○ Escrow.com
● Manual Payment
○ Stripe
○ PayPal

[Continue to Payment]

When the buyer clicks the button:

  1. The selected gateway is submitted.
  2. The selection is validated.
  3. Disabled gateways cannot be submitted.
  4. Manual Payment continues to the next step.
  5. Future gateways display an informative placeholder message.

Files We’ll Modify

Existing

includes/class-payment-page.php

Existing

includes/class-payment-manager.php

Features to Implement

1. Wrap Gateway Selection Inside a Form

Convert the payment gateway section into a proper HTML form.

The form will submit the selected gateway using the POST method.


2. Enable the Continue Button

Replace the disabled placeholder button with an active submit button.

Example:

Continue to Payment

3. Capture Buyer Selection

Read the submitted gateway using:

$_POST['payment_gateway']

Sanitize the value before processing.


4. Validate the Selected Gateway

Verify that:

  • the gateway exists
  • the gateway is currently enabled

If validation fails, display a user-friendly error message.


5. Prepare Gateway Routing

Rather than processing payments directly, create routing logic similar to:

if Manual Payment
    continue to manual payment workflow

if Escrow
    placeholder

if Stripe
    placeholder

if PayPal
    placeholder

This architecture allows future lessons to implement each gateway independently.


User Experience

Current:

Choose Gateway

Manual Payment

Continue (disabled)

After Lesson 73:

Choose Gateway

Manual Payment

Continue to Payment

Upon submission:

Selected Gateway:
Manual Payment

or

Escrow.com integration is coming soon.

depending on the selected gateway.


Architecture Improvement

Before Lesson 73:

Payment Page

↓

Display Gateways

After Lesson 73:

Payment Page

↓

Capture Form

↓

Validate Gateway

↓

Route to Selected Payment Method

↓

Future Gateway Handler

This creates a reusable payment flow that every payment provider will follow.


Benefits

By the end of this lesson, Flipnzee Auctions will have:

  • Functional payment selection form
  • Gateway validation
  • Secure handling of buyer input
  • Centralized routing logic
  • Foundation for integrating Escrow.com, Stripe, PayPal, Razorpay, and cryptocurrency payments

What We Won’t Build Yet

To keep the implementation stable, we are not implementing:

  • Escrow.com API
  • Stripe Checkout
  • PayPal Checkout
  • Razorpay API
  • Cryptocurrency payments
  • Payment confirmation
  • Webhooks
  • Automatic transaction updates

Those will be introduced in future lessons after the payment workflow has been completed.


Expected Outcome

By the end of Lesson 73, the Payment page will evolve from a static gateway selection interface into the first stage of a real checkout process. Buyers will be able to submit their chosen payment method, the plugin will validate the selection securely, and the architecture will be ready to hand control to the appropriate payment gateway implementation in future lessons.

Lesson 74: Manual Payment Instructions and Buyer Confirmation Workflow

Introduction

With the payment gateway routing architecture completed in the previous lessons, buyers can now securely select their preferred payment method. However, selecting Manual Payment currently only displays a placeholder message.

In this lesson, we’ll implement the first real payment workflow in Flipnzee Auctions by displaying manual payment instructions after the buyer selects the Manual Payment gateway.

Rather than integrating a live payment processor immediately, we’ll build a professional workflow that guides buyers through the payment process while preparing the plugin for future automation.


What We’ll Build

After selecting Manual Payment and clicking Continue to Payment, the buyer will see:

  • A payment confirmation notice
  • Transaction reference number
  • Amount to be paid
  • Payment instructions
  • Placeholder bank/account details
  • Buyer checklist
  • “I’ve Completed Payment” button
  • Architecture ready for payment verification in future lessons

Why This Matters

Many marketplace platforms begin with manual payments before integrating payment gateways.

This approach allows:

  • Faster marketplace launch
  • Manual verification by administrators
  • Easy transition to automated gateways later
  • Reusable payment workflow

The same workflow will later support:

  • Escrow.com
  • Stripe
  • PayPal
  • Razorpay
  • USDT Cryptocurrency

Learning Objectives

By the end of this lesson you will:

  • Display professional payment instructions
  • Generate a transaction reference for buyers
  • Show payment amount clearly
  • Build a buyer payment confirmation interface
  • Prepare the plugin for payment verification
  • Create a reusable payment workflow

Planned User Experience

Instead of seeing only:

Manual Payment selected.

The buyer will see something similar to:

Manual Payment

Transaction Reference:
FLIP-000001

Amount:
₹55,555,609.00

Payment Instructions

✓ Transfer the exact amount.

✓ Use the reference number.

✓ Keep your payment receipt.

✓ Click "I've Completed Payment" after payment.

[ I've Completed Payment ]

What We’ll Implement

Step 1

Replace the temporary success message with a real payment instruction section.


Step 2

Generate a payment reference number using the transaction ID.

Example:

FLIP-000001

Step 3

Display the winning bid amount prominently.


Step 4

Display manual payment instructions.


Step 5

Add a buyer checklist before payment.


Step 6

Add an I’ve Completed Payment button.

Initially this button will not update the database.

It simply prepares the workflow for the next lesson.


Files We’ll Modify

Primary file:

includes/class-payment-page.php

Possible future updates:

includes/class-payment-manager.php

Skills You’ll Learn

  • Building multi-step payment workflows
  • Creating reusable payment interfaces
  • Improving user experience
  • Structuring payment pages
  • Preparing for payment verification
  • Designing scalable payment architecture

Expected Result

By the end of Lesson 74, buyers will experience a much more realistic payment process instead of a placeholder message. They’ll receive clear payment instructions, a unique transaction reference, the payment amount, and a confirmation button that prepares the marketplace for the payment verification workflow introduced in the next lesson.


Coming Next

Lesson 75: Recording Buyer Payment Confirmation and Updating Transaction Status

In the next lesson, clicking I’ve Completed Payment will begin updating the transaction status (for example, to Awaiting Verification) and lay the groundwork for seller/admin payment verification.

Lesson 75 Implementation: Refactoring the Buyer Payment Page into Modular Components

As the Flipnzee payment system evolved, the class-payment-page.php file gradually accumulated multiple responsibilities. It was responsible for retrieving transactions, validating payment requests, rendering payment instructions, displaying transaction information, and generating the payment gateway interface.

Rather than continuing to add more features to an increasingly large method, this lesson focused on improving the internal architecture of the payment page through refactoring.

Although no new user-facing functionality was introduced, this refactoring significantly improves code readability, maintainability, and prepares the payment system for future features such as payment proof uploads, administrator verification, and live payment gateway integrations.


Why Refactor?

One of the most common problems in software development is allowing a single function to become too large.

Our original render() method was responsible for:

  • Loading transactions
  • Validating requests
  • Processing payment gateway selection
  • Rendering manual payment instructions
  • Displaying transaction information
  • Displaying the payment gateway selector

Instead of adding even more functionality to this method, we separated the interface into reusable helper methods.


Step 1 – Extract the Transaction Summary

The payment summary table was moved into its own private method.

Instead of embedding the HTML directly inside render(), we created:

private static function render_transaction_summary( $transaction ) {
?>

<h2>Payment</h2>

<table class="widefat striped">

<tr>
    <th>Transaction ID</th>
    <td><?php echo esc_html( $transaction->id ); ?></td>
</tr>

<tr>
    <th>Winning Bid</th>
    <td>
        <?php
        echo esc_html(
            number_format_i18n(
                $transaction->winning_bid,
                2
            )
        );
        ?>
    </td>
</tr>

<tr>
    <th>Status</th>
    <td><?php echo esc_html( ucfirst( $transaction->status ) ); ?></td>
</tr>

<tr>
    <th>Payment Status</th>
    <td><?php echo esc_html( ucfirst( $transaction->payment_status ) ); ?></td>
</tr>

<tr>
    <th>Payment Gateway</th>
    <td>
        <?php
        echo esc_html(
            Flipnzee_Payment_Manager::get_gateway_name( $transaction )
        );
        ?>
    </td>
</tr>

</table>

<?php
}

The main render method now simply calls:

self::render_transaction_summary( $transaction );

Step 2 – Extract the Gateway Selector

Next, the payment gateway selection form was moved into a dedicated helper method.

private static function render_gateway_selector( $gateways ) {
?>

<form method="post">

<?php
wp_nonce_field(
    'flipnzee_payment_action',
    'flipnzee_payment_nonce'
);
?>

<h3>Select Payment Method</h3>

<div class="flipnzee-payment-gateways">

<?php foreach ( $gateways as $gateway_id => $gateway ) : ?>

<p>

<label>

<input
    type="radio"
    name="payment_gateway"
    value="<?php echo esc_attr( $gateway_id ); ?>"
    <?php checked( $gateway['enabled'] ); ?>
    <?php disabled( ! $gateway['enabled'] ); ?>
>

<?php echo esc_html( $gateway['label'] ); ?>

<?php if ( ! $gateway['enabled'] ) : ?>

<em>(Coming Soon)</em>

<?php endif; ?>

</label>

</p>

<?php endforeach; ?>

</div>

<p class="flipnzee-payment-actions">

<button
    type="submit"
    name="flipnzee_payment_completed"
    class="button"
>
I've Completed Payment
</button>

<button
    type="submit"
    name="flipnzee_continue_payment"
    class="button button-primary"
>
Continue to Payment
</button>

</p>

</form>

<?php
}

This method now encapsulates the entire payment gateway interface.


Step 3 – Extract Manual Payment Instructions

The manual payment interface was also separated into its own method.

private static function render_manual_payment( $transaction ) {
?>

<div class="notice notice-success">

    <p><strong>Manual Payment Selected</strong></p>

    <p>Please complete your payment using the instructions below.</p>

</div>

<div class="flipnzee-manual-payment">

<h3>Payment Instructions</h3>

<p>Thank you for choosing Manual Payment.</p>

<p>Please use the transaction reference below when sending your payment.</p>

<table class="widefat striped">

<tr>
    <th>Reference Number</th>
    <td>
        <?php
        echo esc_html(
            'FLIP-' . str_pad(
                $transaction->id,
                6,
                '0',
                STR_PAD_LEFT
            )
        );
        ?>
    </td>
</tr>

<tr>
    <th>Amount</th>
    <td>
        <?php
        echo esc_html(
            number_format_i18n(
                $transaction->winning_bid,
                2
            )
        );
        ?>
    </td>
</tr>

<tr>
    <th>Status</th>
    <td>Awaiting Payment</td>
</tr>

</table>

<h4>Important</h4>

<ul>

<li>Include the reference number with your payment.</li>

<li>Keep proof of payment for verification.</li>

<li>Your transaction will be reviewed before ownership transfer.</li>

</ul>

</div>

<?php
}

Step 4 – Simplify the Gateway Router

Previously, the switch statement contained a large block of HTML for the Manual Payment gateway.

After refactoring, it became much cleaner:

switch ( $selected_gateway ) {

    case 'manual':

        self::render_manual_payment( $transaction );

        break;

    case 'escrow':
        // Escrow placeholder.
        break;

    case 'stripe':
    case 'paypal':
    case 'razorpay':
    case 'crypto':
        // Future gateways.
        break;

    default:
        ?>
        <div class="notice notice-error">
            <p>Unknown payment gateway.</p>
        </div>
        <?php
        break;
}

The routing logic now clearly expresses intent without mixing presentation and control flow.


Benefits of the Refactoring

This refactoring provides several long-term advantages:

  • Cleaner render() method
  • Smaller, focused helper methods
  • Easier debugging
  • Improved readability
  • Better separation of concerns
  • Simpler extension for future payment gateways
  • Reduced code duplication
  • Easier maintenance as the payment workflow grows

Testing

After completing the refactoring:

  • The Buyer Payment Page displayed exactly the same information as before.
  • Manual Payment instructions continued to work.
  • The transaction summary rendered correctly.
  • Payment gateway selection remained functional.
  • No user-facing functionality changed.
  • PHP syntax validation completed successfully.

This confirmed that the refactoring preserved existing behavior while improving the internal architecture.


Lessons Learned

As features accumulate, it is often beneficial to pause and improve the code structure before introducing additional functionality. Separating presentation into dedicated helper methods makes the codebase easier to navigate, simplifies future enhancements, and reduces the risk of introducing bugs when extending existing features.

This lesson also reinforced the importance of keeping rendering logic modular so that future components—such as payment proof uploads, administrator verification, and live gateway integrations—can be added with minimal impact on existing code.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Conclusion

Lesson 75 focused on improving the maintainability of the Buyer Payment Page through thoughtful refactoring. By extracting the transaction summary, payment gateway selector, and manual payment instructions into reusable helper methods, the payment page is now significantly cleaner and better organized. This modular architecture provides a solid foundation for the next stage of development, where buyers will be able to upload payment proof and administrators will verify completed payments before ownership transfer.