Lesson 75: Refactoring the Buyer Payment Page for Better Maintainability

Introduction

As new payment features were added in previous lessons, the class-payment-page.php file began taking on multiple responsibilities. It was loading transactions, processing form submissions, rendering payment instructions, displaying transaction summaries, and generating the payment gateway interface.

Before adding more complex features such as payment proof uploads, transaction status updates, and administrator verification, it became important to reorganize the code into smaller, reusable methods.

In this lesson, we refactor the Buyer Payment Page without changing its functionality. The goal is to improve readability, maintainability, and prepare the payment architecture for future enhancements.


Why Refactor?

Rather than allowing one method to grow indefinitely, we separate different responsibilities into dedicated helper methods.

Benefits include:

  • Cleaner code
  • Easier debugging
  • Better readability
  • Improved reusability
  • Simpler future development
  • Better alignment with object-oriented programming principles

What We Refactored

1. Transaction Summary

The payment summary table was moved into its own method:

private static function render_transaction_summary( $transaction )

This isolates all transaction display logic from the main rendering workflow.


2. Gateway Selection

The payment gateway form was extracted into:

private static function render_gateway_selector( $gateways )

This method now handles:

  • Gateway radio buttons
  • WordPress nonce
  • Payment action buttons

3. Manual Payment Instructions

The manual payment instructions were extracted into:

private static function render_manual_payment( $transaction )

This keeps all manual payment presentation in one place and makes future enhancements (payment proof upload, bank details, etc.) much easier.


4. Cleaner Main Render Method

Instead of containing hundreds of lines of mixed HTML and PHP, the main render() method now delegates responsibilities to helper methods, making the overall flow much easier to understand.


Architecture Before Refactoring

render()

├── Transaction Summary
├── Manual Payment HTML
├── Gateway Form
├── Payment Instructions
├── Form Processing
└── Validation

Architecture After Refactoring

render()
│
├── Process Request
│
├── render_manual_payment()
│
├── render_transaction_summary()
│
└── render_gateway_selector()

This modular approach makes each method easier to read, test, and extend.


Files Modified

includes/class-payment-page.php

Skills Learned

During this lesson, we practiced:

  • Refactoring legacy code
  • Separating responsibilities
  • Creating reusable helper methods
  • Improving object-oriented design
  • Preparing a codebase for future expansion

Outcome

Although this lesson did not introduce new user-facing functionality, it significantly improved the internal architecture of the payment system. The Buyer Payment Page is now modular, easier to maintain, and ready for upcoming features such as payment proof uploads, transaction status updates, administrator verification, and future payment gateway integrations.


Lesson 76: Uploading Payment Proof and Recording Buyer Payment Submission

Introduction

With the Buyer Payment Page now refactored into modular components, the payment system is ready for its next major milestone.

In previous lessons, buyers could:

  • View their transaction details
  • Select a payment gateway
  • Read manual payment instructions
  • Receive a unique payment reference number

However, after making a payment, there is still no mechanism for buyers to notify the marketplace or provide proof that the payment has been completed.

In this lesson, we will implement the Payment Proof Upload feature. Buyers will be able to upload a payment receipt or screenshot directly from the payment page, and Flipnzee will securely store the uploaded file while associating it with the transaction for later administrator review.

This marks the beginning of the complete manual payment verification workflow.


Why This Feature Is Important

Manual payments require evidence before ownership of a digital asset can be transferred.

Instead of asking buyers to send screenshots through email or messaging apps, Flipnzee will manage everything inside the marketplace.

Benefits include:

  • Centralized payment records
  • Better buyer experience
  • Easier administrator verification
  • Improved transaction tracking
  • Foundation for dispute resolution
  • Scalable payment workflow

What We Will Build

After completing this lesson, buyers will be able to:

  • Upload payment proof directly from the payment page.
  • Submit JPG, PNG, or PDF payment receipts.
  • Securely upload files using WordPress.
  • Associate uploaded proof with the transaction.
  • Receive confirmation that the proof has been submitted.
  • Prepare the transaction for administrator verification.

Learning Objectives

By the end of this lesson, you will learn how to:

  • Create secure file upload forms.
  • Handle multipart form submissions.
  • Validate uploaded files.
  • Upload files to the WordPress Media Library.
  • Store attachment IDs against marketplace transactions.
  • Use WordPress upload APIs safely.
  • Prepare transactions for manual verification.

Implementation Roadmap

Step 1

Extend the payment form to support file uploads.


Step 2

Add a Payment Proof upload section.


Step 3

Allow supported file formats:

  • JPG
  • JPEG
  • PNG
  • PDF

Step 4

Secure the upload using the existing WordPress nonce.


Step 5

Upload the file into the WordPress Media Library.


Step 6

Store the uploaded attachment ID against the payment transaction.


Step 7

Display a success confirmation to the buyer.


Step 8

Prepare the transaction for administrator verification.


Files We’ll Modify

Primary files:

includes/class-payment-page.php
includes/class-payment-manager.php

Depending on your current database schema, we may also update the transaction table to include a field for the uploaded payment proof (for example, an attachment ID or file reference).


Expected Buyer Workflow

Buyer Wins Auction
        │
        ▼
Open Payment Page
        │
        ▼
Choose Manual Payment
        │
        ▼
View Payment Instructions
        │
        ▼
Complete Bank Transfer
        │
        ▼
Upload Payment Proof
        │
        ▼
Payment Proof Stored
        │
        ▼
Awaiting Verification

Skills You’ll Learn

During this lesson, you’ll gain experience with:

  • WordPress file upload handling
  • Media Library integration
  • Secure file validation
  • Transaction file associations
  • Payment workflow design
  • Preparing data for administrator approval

Expected Outcome

By the end of Lesson 76, Flipnzee will support one of the most important features of a marketplace payment system: allowing buyers to submit proof of payment directly within the platform. This removes the need for external communication channels and creates a streamlined, auditable workflow for manual payment verification.


Coming Next

Lesson 77: Administrator Payment Verification Dashboard

In the next lesson, administrators will be able to:

  • Review uploaded payment proofs.
  • View associated transaction details.
  • Approve or reject submitted payments.
  • Update payment and transaction statuses.
  • Notify buyers of verification results.
  • Continue the website ownership transfer process.

This will complete the first end-to-end manual payment workflow in the Flipnzee Auction plugin.

Lesson 77: Improving the Buyer Payment Experience After Payment Proof Submission

Overview

In the previous lesson, buyers gained the ability to upload payment proof securely using WordPress’ Media Library. Uploaded receipts were successfully stored, linked to transactions, and duplicate uploads were prevented.

Although the functionality worked correctly, the user experience could still be improved. After submitting payment proof, buyers continued to see payment options and generic transaction statuses, making it unclear whether their submission had been received successfully.

In this lesson, the focus shifts from functionality to user experience by redesigning the payment page after proof submission.


Objectives

By the end of this lesson, we will:

  • Replace generic Pending messages with clearer payment statuses.
  • Hide payment options after payment proof has been uploaded.
  • Display a professional confirmation message.
  • Add a “View Uploaded Payment Proof” link.
  • Prevent buyers from attempting another payment.
  • Prepare the plugin for administrator verification.

Why This Improvement Matters

Once a buyer uploads payment proof, their next question is usually:

  • Did my upload succeed?
  • Will someone review it?
  • What happens next?

Showing payment options again creates uncertainty.

Instead, the page should reassure buyers that everything has been received and explain the next step.


Current Workflow

Current payment flow:

Auction Won
      │
      ▼
Choose Manual Payment
      │
      ▼
Complete Bank Transfer
      │
      ▼
Upload Payment Proof
      │
      ▼
Success Message
      │
      ▼
Payment Options Still Visible ❌

Desired Workflow

After this lesson:

Auction Won
      │
      ▼
Choose Manual Payment
      │
      ▼
Complete Bank Transfer
      │
      ▼
Upload Payment Proof
      │
      ▼
Payment Submitted
      │
      ▼
Waiting for Admin Verification
      │
      ▼
Payment Options Hidden

Planned Improvements

1. Improve Payment Status

Instead of displaying:

Pending

buyers should see something more meaningful, such as:

Submitted for Verification

or

Awaiting Verification

2. Hide Payment Method Selection

Once payment proof exists, buyers should no longer see:

  • Manual Payment
  • Escrow
  • Stripe
  • PayPal
  • Razorpay
  • USDT

These options are no longer relevant after submission.


3. Hide Action Buttons

Buttons such as:

  • Continue to Payment
  • I’ve Completed Payment

should disappear after payment proof submission.


4. Display a Confirmation Card

Instead of payment controls, buyers should see a professional confirmation message.

Example:

✓ Payment Proof Submitted

Reference:
FLIP-000001

Payment Status:
Submitted for Verification

Thank you.

Our team will review your payment shortly.

Ownership transfer will begin once payment has been verified.

5. Add “View Uploaded Proof”

Since the uploaded receipt already exists in the WordPress Media Library, buyers should be able to confirm exactly what they uploaded.

Example:

View Uploaded Receipt

This will help buyers verify that the correct document was submitted.


6. Improve Transaction Summary

The transaction table should become more informative.

Example:

FieldValue
Transaction1
Winning Bid₹55,555,609
Payment StatusSubmitted for Verification
Payment MethodManual Payment
Payment ProofUploaded ✓

7. Introduce a Timeline

A simple progress indicator makes the payment journey much easier to understand.

✓ Auction Won

✓ Manual Payment Selected

✓ Payment Proof Uploaded

⏳ Verification Pending

□ Ownership Transfer

8. Prepare for Admin Approval

This lesson also prepares the foundation for administrator workflows.

Future lessons will allow administrators to:

  • Review uploaded receipts.
  • Approve payments.
  • Reject invalid payment proofs.
  • Request new payment proof.
  • Notify buyers automatically.

Expected Outcome

After completing this lesson:

  • Buyers clearly understand their payment has been received.
  • Duplicate payment attempts are eliminated.
  • The payment page becomes cleaner and more professional.
  • The plugin is ready for administrator verification features.
  • The overall user experience aligns with real-world marketplace payment workflows.

What You Will Learn

Throughout this lesson, you will learn how to:

  • Render different interfaces based on transaction state.
  • Improve user experience using conditional rendering.
  • Present payment progress more clearly.
  • Separate buyer actions from administrator actions.
  • Design workflows that scale as new payment gateways are added.

Next Lesson Preview

Lesson 78 – Building the Administrator Payment Verification Dashboard

In the next lesson, we will begin the administrator side of the payment system by creating a dashboard where site administrators can:

  • View submitted payment proofs.
  • Open uploaded receipts directly from the Media Library.
  • Approve or reject payments.
  • Update transaction statuses.
  • Trigger the next stage of the website ownership transfer workflow.

This will complete the first full end-to-end manual payment verification process in the Flipnzee Auctions plugin.

Lesson 76: Building Secure Payment Proof Uploads for Manual Payments in the Flipnzee Auctions Plugin

In the previous lesson, the Flipnzee Auctions plugin was refactored to separate the payment page into reusable methods. With the foundation now in place, the next logical step was to allow buyers to securely upload proof of payment after completing a manual bank transfer or other offline payment.

This lesson focused on implementing a complete payment proof upload workflow using WordPress’ built-in Media Library functions while ensuring security through nonce verification and preventing duplicate uploads.


Objective

Implement a secure payment proof upload system that:

  • Allows buyers to upload payment receipts.
  • Stores uploaded files in the WordPress Media Library.
  • Saves the attachment ID in the transaction table.
  • Prevents duplicate uploads.
  • Displays appropriate confirmation messages.
  • Prepares the plugin for future admin verification.

Step 1 – Creating the Upload Section

A new upload section was added beneath the manual payment instructions.

<h3>Upload Payment Proof</h3>

<p>
After completing your payment, upload your receipt or screenshot below.
</p>

<form
    method="post"
    enctype="multipart/form-data"
>

Using multipart/form-data is essential whenever files are uploaded.


Step 2 – Protecting the Form with a WordPress Nonce

Every upload request should be protected against CSRF attacks.

wp_nonce_field(
    'flipnzee_upload_proof',
    'flipnzee_upload_nonce'
);

The nonce is later verified before processing the upload.


Step 3 – Creating the File Input

The upload field accepts common payment proof formats.

<input
    type="file"
    name="flipnzee_payment_proof"
    accept=".jpg,.jpeg,.png,.pdf"
    required
>

Supported file types include:

  • JPG
  • JPEG
  • PNG
  • PDF

Step 4 – Detecting Upload Requests

Inside the main render method, the plugin detects whether the buyer submitted a payment proof.

if (
    isset( $_POST['flipnzee_upload_payment_proof'] ) &&
    isset( $_FILES['flipnzee_payment_proof'] ) &&
    ! empty( $_FILES['flipnzee_payment_proof']['name'] )
) {

}

This ensures uploads are only processed when the upload button is pressed.


Step 5 – Verifying the Nonce

Before accepting any uploaded file, the nonce is validated.

if (
    ! isset( $_POST['flipnzee_upload_nonce'] ) ||
    ! wp_verify_nonce(
        sanitize_text_field(
            wp_unslash( $_POST['flipnzee_upload_nonce'] )
        ),
        'flipnzee_upload_proof'
    )
) {
    return '<p>Security check failed.</p>';
}

This protects the upload endpoint from forged requests.


Step 6 – Loading WordPress Upload Libraries

Instead of manually moving files, WordPress provides built-in upload helpers.

require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/image.php';

These libraries automatically handle:

  • Uploads
  • File validation
  • Image metadata
  • Media Library integration

Step 7 – Uploading the File

The upload is performed using WordPress’ native API.

$attachment_id = media_handle_upload(
    'flipnzee_payment_proof',
    0
);

Successful uploads immediately become Media Library attachments.


Step 8 – Saving the Attachment ID

After a successful upload, the attachment ID is saved against the transaction.

Flipnzee_Payment_Manager::save_payment_proof(
    $transaction->id,
    $attachment_id
);

This updates the transaction record with:

  • payment_proof_id
  • payment_status

Step 9 – Refreshing the Transaction

One subtle issue appeared during testing.

Although the database updated successfully, the current $transaction object still contained the old values because it had been loaded before the upload.

Refreshing the transaction solved the issue.

$transaction = Flipnzee_Payment_Manager::get_transaction(
    $transaction->id
);

This immediately reflects the latest payment information.


Step 10 – Preventing Duplicate Uploads

Instead of always displaying the upload form, the page now checks whether a payment proof already exists.

<?php if ( empty( $transaction->payment_proof_id ) ) : ?>

<!-- Upload Form -->

<?php else : ?>

<div class="notice notice-success">

    <p>

        <strong>Payment Proof Already Submitted.</strong>

        Your payment proof has already been uploaded and is awaiting verification by the Flipnzee team.

    </p>

</div>

<?php endif; ?>

This prevents accidental duplicate submissions.


Step 11 – Testing

The upload workflow was tested thoroughly.

Successful tests included:

  • Uploading PNG payment receipts.
  • Verifying files appear in the WordPress Media Library.
  • Confirming payment_proof_id is stored in the database.
  • Confirming payment_status changes to submitted.
  • Confirming duplicate uploads are prevented.
  • Confirming success messages appear after upload.

Challenges Encountered

Several issues were encountered during implementation.

Transaction Not Refreshing

Although the database updated correctly, the upload form continued appearing because the transaction object had not been refreshed after saving the payment proof.

Reloading the transaction solved this issue.


Media Library Confusion

Initially it appeared that uploads were failing because the uploaded image was not immediately visible.

The issue turned out to be Media Library filtering and caching rather than the upload itself.


Conditional Rendering

Wrapping the upload form inside a conditional block required careful placement of the opening and closing PHP tags to avoid syntax errors.

Once corrected, the page behaved exactly as expected.


What Was Achieved

By the end of this lesson, the Flipnzee Auctions plugin could:

  • Accept secure payment proof uploads.
  • Store uploaded receipts in the Media Library.
  • Save attachment IDs with transactions.
  • Prevent duplicate uploads.
  • Display confirmation messages.
  • Prepare transactions for future verification.

Lessons Learned

Several important WordPress development concepts were reinforced:

  • Always use nonces when processing forms.
  • Prefer WordPress Media APIs over custom upload code.
  • Refresh database objects after updates.
  • Use conditional rendering to improve user experience.
  • Store Media Library attachment IDs instead of file paths whenever possible.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Next Lesson

In Lesson 77, the payment experience will be polished further by:

  • Displaying Submitted for Verification instead of Pending.
  • Hiding payment options once proof has been uploaded.
  • Showing a cleaner buyer confirmation page.
  • Adding links to view uploaded payment proof.
  • Beginning the admin verification workflow.

This will complete the buyer-side manual payment journey and prepare the plugin for administrator approval of submitted payments.

Lesson 74 Implementation: Displaying Professional Manual Payment Instructions on the Payment Page

After completing the payment gateway selection workflow in the previous lessons, the next improvement was making the payment page more informative for buyers who choose Manual Payment.

Previously, selecting Manual Payment only displayed a simple confirmation message. In this lesson, the payment page was enhanced to show a professional payment instruction section containing a unique payment reference, payment amount, current status, and important guidance for the buyer.


What We Built

The payment page now displays a dedicated Payment Instructions section whenever the buyer selects Manual Payment.

The section includes:

  • Unique payment reference number
  • Winning bid amount
  • Current payment status
  • Important payment instructions
  • Existing transaction details remain visible below

This provides buyers with the information they need before sending payment.


Step 1 – Detect Manual Payment Selection

After validating the form submission and selected gateway, the payment page checks which payment method the buyer selected.

switch ( $selected_gateway ) {

    case 'manual':

        // Display manual payment instructions.

        break;

    default:

        // Unsupported gateway.

        break;
}

This structure prepares the plugin for adding more gateways like Escrow.com, Stripe, PayPal and USDT in future lessons.


Step 2 – Create the Manual Payment Instruction Section

Inside the Manual Payment case, a dedicated container was added.

<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>

</div>

This creates a clear visual separation between payment instructions and transaction information.


Step 3 – Generate a Unique Payment Reference

Instead of using only the transaction ID, a formatted payment reference was generated.

<?php

echo esc_html(

    'FLIP-' . str_pad(

        $transaction->id,

        6,

        '0',

        STR_PAD_LEFT

    )

);

?>

Example:

FLIP-000001

Using a formatted reference looks much more professional and is easier for buyers to include in payment notes.


Step 4 – Display Important Payment Information

A table was created to display the essential payment information.

<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>

This gives buyers an organized summary before making payment.


Step 5 – Add Important Buyer Instructions

An instruction list was added below the payment summary.

<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>

These reminders help reduce payment mistakes and prepare buyers for the verification process.


Final Result

After selecting Manual Payment, buyers now see:

  • Professional payment instruction heading
  • Payment reference number
  • Winning amount
  • Awaiting payment status
  • Important payment reminders
  • Original transaction details below

The payment page now feels much closer to a production-ready marketplace instead of a placeholder page.


What I Learned

This lesson demonstrated that payment pages should do much more than simply display transaction details. Buyers need clear instructions, a recognizable payment reference, and confirmation of the amount and status before making payment.

Generating a formatted reference number and presenting information in a structured table significantly improves usability and prepares the payment workflow for future enhancements.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


What’s Next?

In Lesson 75, we will build the Payment Proof Upload feature, allowing buyers to submit proof of payment after completing a manual transfer. This will move the Flipnzee payment workflow one step closer to a complete marketplace transaction process.

Lesson 73 Implementation: Processing Payment Gateway Selection Securely in Flipnzee

In the previous lesson, the payment page displayed multiple payment gateways dynamically. However, clicking Continue to Payment did not actually process the buyer’s selection.

In this lesson, the payment page was enhanced to securely process the selected payment gateway using WordPress security best practices. This establishes the routing architecture that future payment integrations such as Escrow.com, Stripe, PayPal, Razorpay, and USDT Cryptocurrency will use.


What Was Implemented

The payment page now:

  • Processes the submitted payment form
  • Verifies the WordPress nonce
  • Sanitizes user input
  • Validates the selected gateway
  • Routes requests using a switch statement
  • Displays gateway-specific responses
  • Prepares the plugin for future payment integrations

This completes the payment gateway routing layer.


Step 1: Detect Form Submission

The payment page first checks whether the buyer has submitted the payment form.

if ( isset( $_POST['flipnzee_continue_payment'] ) ) {

    // Process payment

}

This ensures the processing code only runs after the buyer clicks Continue to Payment.


Step 2: Verify the WordPress Nonce

Before processing any submitted data, the request is verified using a WordPress nonce.

if (
    ! isset( $_POST['flipnzee_payment_nonce'] ) ||
    ! wp_verify_nonce(
        sanitize_text_field(
            wp_unslash( $_POST['flipnzee_payment_nonce'] )
        ),
        'flipnzee_payment_action'
    )
) {
    return '<p>Security check failed.</p>';
}

Why?

This protects the payment page from:

  • CSRF attacks
  • Forged form submissions
  • External malicious requests

Using nonces is a standard WordPress security practice.


Step 3: Sanitize the Selected Gateway

The selected payment gateway is retrieved safely.

$selected_gateway = '';

if ( isset( $_POST['payment_gateway'] ) ) {

    $selected_gateway = sanitize_text_field(
        wp_unslash( $_POST['payment_gateway'] )
    );

}

This removes unsafe input before it reaches the application logic.


Step 4: Validate the Gateway

Before routing, the submitted gateway is checked against the list of available gateways.

if ( ! isset( $gateways[ $selected_gateway ] ) ) {

    return '<p>Invalid payment gateway selected.</p>';

}

This prevents invalid or manipulated gateway values from being processed.


Step 5: Route Using a Switch Statement

The payment gateway router directs each gateway to its own processing block.

switch ( $selected_gateway ) {

    case 'manual':
        ?>
        <div class="notice notice-success">
            <p>
                Manual Payment selected.
                Payment instructions will be displayed in the next lesson.
            </p>
        </div>
        <?php
        break;

    case 'escrow':
        ?>
        <div class="notice notice-info">
            <p>
                Escrow.com integration will be available in a future release.
            </p>
        </div>
        <?php
        break;

    case 'stripe':
    case 'paypal':
    case 'razorpay':
    case 'crypto':
        ?>
        <div class="notice notice-warning">
            <p>
                This payment gateway is not yet available.
            </p>
        </div>
        <?php
        break;

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

This routing structure keeps each payment provider isolated, making future integrations straightforward.


Testing the Implementation

After updating the payment page:

  1. Open the buyer payment page.
  2. Select Manual Payment.
  3. Click Continue to Payment.

The page now displays:

Manual Payment selected. Payment instructions will be displayed in the next lesson.

The transaction information remains visible, confirming that the form was processed successfully.


Why This Design Matters

Instead of embedding payment logic directly into the page, a routing layer has been introduced.

This provides several advantages:

  • Cleaner code organization
  • Easier maintenance
  • Independent gateway implementations
  • Better scalability
  • Simpler testing
  • Future extensibility

When additional gateways are implemented, each will simply receive its own case inside the existing router without affecting the others.


Lessons Learned

During implementation, several improvements were made:

  • Used WordPress nonces to secure form submissions.
  • Sanitized all user-submitted values before processing.
  • Validated gateway IDs against the registered gateway list.
  • Built a centralized gateway routing mechanism.
  • Kept the payment architecture flexible for future integrations.
  • Successfully tested Manual Payment routing without affecting existing transaction data.

Current Payment Flow

Buyer Opens Payment Page
           │
           ▼
Select Payment Gateway
           │
           ▼
Continue to Payment
           │
           ▼
Verify WordPress Nonce
           │
           ▼
Sanitize User Input
           │
           ▼
Validate Gateway
           │
           ▼
Gateway Router (switch)
           │
 ┌─────────┼───────────────┐
 │         │               │
 ▼         ▼               ▼
Manual   Escrow        Future Gateways
Payment  (Coming Soon) (Stripe, PayPal,
                         Razorpay, USDT)

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Conclusion

Lesson 73 transformed the payment page from a static gateway selector into a secure routing system capable of processing buyer selections. By combining nonce verification, input sanitization, gateway validation, and switch-based routing, Flipnzee now has a solid payment processing foundation. Future lessons can build upon this architecture to implement real payment instructions, proof-of-payment submission, and live integrations with services such as Escrow.com, Stripe, PayPal, Razorpay, and USDT Cryptocurrency.

Lesson 72 Implementation: Building a Future-Ready Payment Gateway Selection Interface

As the Flipnzee Auctions plugin continues to evolve into a professional website marketplace, one of the most important architectural decisions is how payment gateways will be integrated. Rather than hardcoding a single payment provider, this lesson introduces a flexible gateway selection system that can easily support multiple payment methods in the future.

Although no real payment gateways are connected yet, the plugin now provides a scalable framework for adding Escrow.com, Stripe, PayPal, Razorpay, cryptocurrency payments, and other providers without redesigning the payment page.


Why This Lesson Was Needed

Until the previous lesson, buyers could only see the transaction details and a placeholder payment gateway.

While functional, that approach wasn’t scalable. Every time a new payment provider was added, the payment page would need to be rewritten.

Instead, the payment page should simply ask:

“Which payment gateways are currently available?”

The Payment Manager should answer that question.

This separation of responsibilities makes the code easier to maintain and extend.


Objectives

In this lesson we:

  • Centralized payment gateway definitions
  • Added a helper method to retrieve available gateways
  • Introduced Escrow.com as the planned primary marketplace payment method
  • Generated the payment method list dynamically
  • Displayed future gateways as disabled
  • Added a disabled “Continue to Payment” button
  • Prepared the plugin for future payment gateway integrations

Step 1 – Centralizing Available Payment Gateways

Inside:

includes/class-payment-manager.php

a new helper method was introduced:

/**
 * Get available payment gateways.
 *
 * @return array
 */
public static function get_available_gateways() {

    return array(

        'escrow' => array(
            'label'   => 'Escrow.com (Recommended)',
            'enabled' => false,
        ),

        '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,
        ),

    );

}

Instead of hardcoding gateway names inside the payment page, all available gateways are now managed from a single location.


Step 2 – Loading Gateways in the Payment Page

After validating the transaction, the payment page now requests the available gateways from the Payment Manager.

$gateways = Flipnzee_Payment_Manager::get_available_gateways();

This keeps the page independent from payment logic and allows new gateways to be introduced without modifying the frontend.


Step 3 – Rendering Gateway Options Dynamically

The payment page now loops through the available gateways to generate the interface.

<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>

This approach automatically displays every configured gateway without manually writing HTML for each payment provider.


Step 4 – Adding a Checkout Placeholder

Since actual payment processing has not yet been implemented, a disabled button was added.

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

    <button
        type="button"
        class="button button-primary"
        disabled
    >
        Continue to Payment (Coming Soon)
    </button>

</p>

The button clearly communicates that payment processing will be introduced in a future lesson while maintaining a professional checkout layout.


Why Escrow.com Appears First

During implementation, the payment architecture was adjusted to better reflect Flipnzee’s purpose.

Instead of treating Stripe or PayPal as the primary payment method, the gateway list now starts with:

  • Escrow.com (Recommended)
  • Manual Payment
  • Stripe
  • PayPal
  • Razorpay
  • USDT Cryptocurrency

Since Flipnzee is designed as a marketplace for buying and selling websites, Escrow.com is expected to become the primary payment solution once its API integration is implemented.

Until then, it remains disabled and marked as “Coming Soon.”


Testing

After implementing the changes:

  • The Payment page continued displaying transaction information correctly.
  • Payment gateways were loaded dynamically.
  • Manual Payment appeared as the only selectable option.
  • Future gateways appeared disabled.
  • Escrow.com was displayed as the recommended marketplace payment solution.
  • The “Continue to Payment” button appeared in a disabled state.

No PHP syntax errors were encountered during testing.


Lessons Learned

This lesson reinforced several important software design principles:

  • Business logic should be separated from presentation logic.
  • Payment providers should be managed centrally.
  • Dynamic rendering reduces future maintenance.
  • Building a scalable architecture early simplifies later integrations.
  • Placeholder interfaces help guide future development while keeping the application stable.

Current Progress

The Flipnzee Auctions plugin now includes:

  • Auction management
  • Transaction creation
  • Purchase history
  • Individual purchase details
  • Dedicated payment page
  • Payment gateway architecture
  • Dynamic gateway selection interface
  • Escrow-ready payment framework

Although real payment processing has not yet been added, the plugin now has a solid architectural foundation that will make future integrations significantly easier.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Next Lesson

In Lesson 73, we’ll move beyond the static gateway list and begin building the actual payment flow by allowing buyers to submit their selected payment method, validating their choice, storing it with the transaction, and preparing the plugin to route users toward the appropriate payment handler. This will transform the current placeholder interface into the first stage of a working checkout process.

Lesson 71 Implementation: Introducing the Payment Manager for Transaction Validation

After successfully creating the buyer payment page in the previous lesson, the next logical improvement was to separate payment-related business logic from the presentation layer. Instead of allowing the payment page to directly decide whether a transaction could be paid, a dedicated Payment Manager class was introduced.

This lesson focuses on improving the plugin architecture while preparing the foundation for future payment gateway integrations such as Stripe, PayPal, Razorpay, or manual bank transfer.


Objective

The goals of this lesson were to:

  • Create a dedicated Flipnzee_Payment_Manager class.
  • Centralize payment validation logic.
  • Validate transactions before displaying the payment page.
  • Prepare a placeholder method for future payment gateway integrations.
  • Keep the payment page clean and easier to maintain.

Why This Refactoring Was Needed

In Lesson 70, the payment page displayed transaction details directly after fetching the transaction.

As more features are added, such as:

  • payment expiry
  • completed payments
  • cancelled transactions
  • multiple payment gateways

placing all validation logic inside the page would quickly become difficult to maintain.

Instead, all payment-related decisions should live inside a dedicated manager.

This follows the Single Responsibility Principle, where each class has one clear responsibility.


Step 1 — Creating the Payment Manager

A new file was created:

includes/class-payment-manager.php

The initial class structure:

<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Flipnzee_Payment_Manager {

}

This class will eventually become the central place for everything related to buyer payments.


Step 2 — Registering the New Class

The loader was updated so WordPress loads the new class automatically.

Example:

require_once FLIPNZEE_AUCTIONS_PLUGIN_DIR . 'includes/class-payment-manager.php';

Step 3 — Moving Validation into the Manager

Instead of checking the transaction status directly inside the payment page, a reusable validation method was created.

public static function can_pay( $transaction ) {

    if ( ! $transaction ) {
        return false;
    }

    if ( strtolower( trim( $transaction->status ) ) !== 'pending' ) {
        return false;
    }

    return true;
}

Why strtolower()?

During testing, it was discovered that database values may use different capitalization.

Examples:

Pending
pending
PENDING

Using:

strtolower( trim( $transaction->status ) )

ensures all of these are treated consistently.


Step 4 — Validating the Transaction

The payment page now retrieves the transaction:

$transaction = Flipnzee_Payment_Manager::get_transaction(
    $transaction_id
);

If nothing is found:

if ( ! $transaction ) {
    return '<p>Transaction not found.</p>';
}

Then the Payment Manager determines whether payment is still allowed.

if ( ! Flipnzee_Payment_Manager::can_pay( $transaction ) ) {
    return '<p>This transaction is no longer available for payment.</p>';
}

This keeps the page itself very clean.


Step 5 — Preparing Gateway Support

Since payment gateways will be implemented in future lessons, a placeholder method was added.

public static function get_gateway_name( $transaction ) {

    return 'Manual Payment (Coming Soon)';
}

The payment page simply calls:

echo esc_html(
    Flipnzee_Payment_Manager::get_gateway_name( $transaction )
);

Later, this method will automatically return:

  • Manual Bank Transfer
  • Stripe
  • Razorpay
  • PayPal

without changing the payment page.


Debugging Along the Way

During implementation, a few useful issues were discovered.

1. Transaction Status Case Sensitivity

Initially the validation checked:

$transaction->status !== 'Pending'

However, the database stored:

pending

As a result, every payment was incorrectly rejected.

The validation was updated to:

strtolower( trim( $transaction->status ) ) !== 'pending'

making it much more reliable.


2. Missing Payment Gateway Column

An attempt was made to display:

$transaction->payment_gateway

This produced an undefined property warning because the database table does not yet contain a payment_gateway column.

Instead of adding a temporary workaround, the gateway display was moved into:

Flipnzee_Payment_Manager::get_gateway_name()

which currently returns a placeholder while the database schema is prepared in a future lesson.


Testing

Several scenarios were tested.

✅ Existing transaction loads correctly.

✅ Pending transaction is accepted.

✅ Invalid transaction ID displays:

Transaction not found.

✅ Placeholder payment gateway displays:

Manual Payment (Coming Soon)

No PHP warnings remain.


Final Result

The payment page now displays:

  • Transaction ID
  • Winning Bid
  • Status
  • Payment Status
  • Payment Gateway

with validation handled entirely by the Payment Manager.

The interface remains clean while the underlying architecture becomes much more maintainable.

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


What Was Learned

This lesson demonstrated the value of separating business logic from presentation.

Instead of embedding validation throughout the payment page, all payment-related decisions are now centralized in a dedicated manager. This approach makes the code easier to read, easier to test, and far simpler to extend as new payment gateways and payment workflows are introduced.

It also highlighted the importance of real-world debugging—such as handling inconsistent database values (e.g., Pending vs. pending) and recognizing when a database schema needs to evolve rather than patching around missing fields.

With the Flipnzee_Payment_Manager now in place, the plugin has a solid foundation for implementing gateway-specific payment processing in upcoming lessons while keeping the payment page itself clean and focused.

Lesson 70: Building a Dedicated Payment Page for Flipnzee Auctions

After completing the buyer purchase history and purchase details pages in the previous lesson, the next logical step was to create a dedicated payment page. Instead of redirecting buyers to a non-existent URL after clicking “Pay Now”, the plugin now provides a proper payment page that serves as the foundation for future payment gateway integration.

Although no payment gateway is connected yet, this lesson establishes the complete page architecture that future lessons will build upon.


Objective

The goal of this lesson was to:

  • Create a dedicated payment page.
  • Register a new shortcode for the payment page.
  • Display transaction information securely.
  • Ensure only logged-in users can access the page.
  • Prepare the plugin for Stripe, PayPal and other payment integrations.

What We Built

The payment workflow now looks like this:

Completed Auction
        │
        ▼
Transaction Created
        │
        ▼
Buyer clicks "Pay Now"
        │
        ▼
/payment/?transaction_id=1
        │
        ▼
Payment Page
        │
        ▼
(Future)
Stripe / PayPal / Crypto Payment

Step 1 — Create a New Payment Page Class

A new file was created:

includes/class-payment-page.php

The file begins with the standard WordPress security check.

<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Flipnzee_Payment_Page {

    public static function render() {

        if ( ! is_user_logged_in() ) {
            return '<p>Please log in to continue.</p>';
        }

        ob_start();

        $transaction_id = isset( $_GET['transaction_id'] )
            ? absint( $_GET['transaction_id'] )
            : 0;

        // Display payment information here.

        return ob_get_clean();
    }
}

Step 2 — Register a New Shortcode

The shortcode registry inside

includes/class-shortcodes.php

was extended with a new shortcode.

add_shortcode(
    'flipnzee_payment_page',
    array(
        'Flipnzee_Payment_Page',
        'render'
    )
);

This allows WordPress pages to render the payment interface using:

[flipnzee_payment_page]

Step 3 — Load the Payment Page Class

The plugin loader was updated so the new class becomes available throughout the plugin.

Example:

require_once FLIPNZEE_PLUGIN_PATH . 'includes/class-payment-page.php';

Without loading the class, WordPress would be unable to locate the shortcode callback.


Step 4 — Retrieve the Transaction ID

The page accepts the transaction through the URL.

Example:

/payment/?transaction_id=1

The transaction ID is safely extracted using:

$transaction_id = isset( $_GET['transaction_id'] )
    ? absint( $_GET['transaction_id'] )
    : 0;

Using absint() ensures only positive integer IDs are accepted.


Step 5 — Fetch Transaction Details

Using the transaction ID, the plugin queries the transaction table.

Example:

global $wpdb;

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

$transaction = $wpdb->get_row(
    $wpdb->prepare(
        "SELECT * FROM {$table} WHERE id = %d",
        $transaction_id
    )
);

This returns the complete transaction record for display.


Step 6 — Display Payment Information

The page currently displays essential information including:

  • Transaction ID
  • Winning Bid
  • Transaction Status
  • Payment Status

Example output:

Payment

Transaction ID     1
Winning Bid        ₹55,555,609
Status             Pending
Payment Status     Pending

This provides buyers with confirmation that the transaction exists before payment processing is added.


Step 7 — Create a WordPress Payment Page

A new WordPress page was created:

Payment

The page content contains only the shortcode:

[flipnzee_payment_page]

This keeps presentation separate from business logic, making the system easier to maintain.


Testing

The payment page was tested by visiting:

/payment/?transaction_id=1

The page correctly displayed:

  • Transaction ID
  • Winning Bid
  • Pending Status
  • Pending Payment Status

The previous 404 Not Found error was successfully resolved.


Files Modified

includes/class-payment-page.php (new)
includes/class-shortcodes.php
includes/class-loader.php (or plugin loader)

Download Source Code

Download the starting version of the plugin before the lesson:

Download the completed version after this lesson:


Lessons Learned

During implementation, several important WordPress plugin development concepts were reinforced:

  • Create reusable functionality using dedicated classes.
  • Register features using WordPress shortcodes.
  • Load new classes through the plugin loader.
  • Validate user input using absint().
  • Protect pages by requiring user authentication.
  • Use output buffering (ob_start() / ob_get_clean()) for shortcode rendering.
  • Keep page layout separate from business logic.

Current Workflow

Auction Ends
      │
      ▼
Winner Determined
      │
      ▼
Transaction Created
      │
      ▼
"My Purchases"
      │
      ▼
Pay Now
      │
      ▼
Payment Page
      │
      ▼
(Future)
Payment Gateway Integration

What’s Next?

With the payment page now in place, the plugin is ready for the next phase of development. Future lessons will focus on transforming this informational page into a fully functional checkout by adding payment gateway integration, order summaries, payment processing, status updates, and buyer/seller notifications.

Lesson 70 establishes the foundation that all future payment functionality will build upon.

Lesson 71: Preparing the Payment Gateway Architecture for Future Integrations

Introduction

With a dedicated buyer payment page now operational, the next step is to prepare the plugin for actual payment gateway integration. Rather than immediately connecting to a provider like Stripe or PayPal, it is better to first build a clean, reusable architecture that allows multiple payment gateways to be added later without rewriting the auction workflow.

In this lesson, we’ll introduce a centralized payment manager that becomes responsible for generating payment requests, validating transactions, and routing buyers to the selected payment gateway. Although no real payment processing will occur yet, this lesson lays the foundation for supporting Stripe, PayPal, Razorpay, cryptocurrency payments, and additional gateways in future releases.


Learning Objectives

By the end of this lesson, you will learn how to:

  • Design a scalable payment architecture.
  • Separate payment logic from page rendering.
  • Create a dedicated Payment Manager class.
  • Validate transactions before initiating payment.
  • Prepare the plugin for multiple payment gateways.
  • Keep the codebase modular and maintainable.

Why This Lesson Is Important

A common mistake is embedding payment code directly inside the payment page shortcode. That approach quickly becomes difficult to maintain when additional gateways are introduced.

Instead, we’ll separate responsibilities:

  • Payment Page → displays information to the buyer.
  • Payment Manager → handles payment processing logic.
  • Gateway Classes (future lessons) → communicate with Stripe, PayPal, Razorpay, crypto wallets, etc.

This layered architecture follows good software engineering principles and makes the plugin easier to extend.


What We’ll Build

At the end of this lesson, the payment flow will look like this:

Buyer
   │
   ▼
Payment Page
   │
   ▼
Payment Manager
   │
   ▼
Selected Gateway
   │
   ├── Stripe (future)
   ├── PayPal (future)
   ├── Razorpay (future)
   └── Crypto (future)

Planned Implementation

During this lesson we will:

Step 1

Create

includes/class-payment-manager.php

Step 2

Move payment-related business logic into this class.


Step 3

Add a function to validate a transaction before payment begins.


Step 4

Create a placeholder method that returns the payment URL for the selected gateway.


Step 5

Update the payment page so it requests payment information from the Payment Manager instead of containing all business logic itself.


Step 6

Register and load the new class using the plugin loader.


Expected Folder Structure

includes/

class-payment-manager.php
class-payment-page.php
class-transaction-manager.php
class-my-purchases.php
class-my-purchase-details.php

Benefits

After completing this lesson, the plugin will have:

  • Better separation of concerns.
  • Easier maintenance.
  • Cleaner code.
  • Support for multiple gateways.
  • Simpler testing.
  • Future-proof architecture.

Skills You’ll Learn

  • Object-Oriented Programming (OOP)
  • Separation of Concerns
  • WordPress Plugin Architecture
  • Business Logic vs Presentation
  • Designing Extensible Systems
  • Preparing APIs for Third-Party Integrations

What Comes Next?

With the Payment Manager in place, the next lessons can focus on implementing real payment gateways without modifying the auction or transaction workflow.

A possible roadmap is:

  • Lesson 72: Creating the Payment Manager and Transaction Validation
  • Lesson 73: Adding a Gateway Interface and Default Gateway Selection
  • Lesson 74: Integrating the First Payment Gateway (e.g., Stripe or Razorpay Sandbox)
  • Lesson 75: Handling Payment Callbacks and Updating Transaction Status

By first building the architecture rather than jumping straight into gateway code, the Flipnzee Auctions plugin will remain clean, scalable, and capable of supporting multiple payment providers as the marketplace grows.