Skip to content

Instantly share code, notes, and snippets.

@shayanabbas
Created December 3, 2024 23:50
Show Gist options
  • Save shayanabbas/6adf045dc9883b7daeb3875a121e8467 to your computer and use it in GitHub Desktop.
Save shayanabbas/6adf045dc9883b7daeb3875a121e8467 to your computer and use it in GitHub Desktop.
OL Project

Project Documentation for BiasPay Integration with OlympusLabs.uk

Project Overview

The goal of this project is to enable the OlympusLabs.uk WooCommerce-based store to utilize the BiasPay payment gateway, which is registered for the Shopify-based Olympus-Labs.com domain. To achieve this, we will develop:

  1. A WooCommerce plugin to integrate BiasPay with OlympusLabs.uk.
  2. A Proxy API hosted on a subdomain (pay.olympus-labs.com) to securely mediate communication between the WooCommerce plugin and the BiasPay API.

1. WooCommerce Plugin Development

Plugin Features and Flow

  1. User Interface:

    • Add BiasPay as a payment option during the checkout process.
    • Configure settings in the WooCommerce admin panel:
      • Enable/Disable BiasPay.
      • Enter BiasPay API credentials.
      • Set Proxy API URL (https://pay.olympus-labs.com).
  2. Checkout Process:

    • When a customer selects BiasPay, the plugin collects necessary order details (e.g., total amount, currency, order ID).
    • The plugin sends these details to the Proxy API endpoint for processing.
    • The Proxy API communicates with BiasPay and returns the result (success, failure, or pending).
    • Based on the result, the plugin updates the WooCommerce order status:
      • Success: Mark the order as "Completed".
      • Failure: Mark the order as "Failed".
      • Pending: Mark the order as "Pending Payment".
  3. Error Handling:

    • Log errors in a designated log file.
    • Display user-friendly error messages to customers.
    • Retries for failed API requests with exponential backoff.

Plugin Files and Structure

  • Folder Name: woocommerce-biaspay-plugin
  • Main Files:
    • woocommerce-biaspay.php: Plugin bootstrap file.
    • includes/: Core functionality:
      • class-biaspay-gateway.php: Handles payment gateway logic.
      • class-biaspay-api.php: Handles communication with Proxy API.
      • class-biaspay-logger.php: Handles logging.
    • assets/: For JS and CSS (if needed).
    • templates/: Custom templates for checkout UI.

Configuration in WooCommerce

  • Register BiasPay as a payment gateway in WooCommerce by extending WC_Payment_Gateway.

  • Add settings fields in the WooCommerce admin for BiasPay:

    add_filter('woocommerce_payment_gateways', 'add_biaspay_gateway_class');
    function add_biaspay_gateway_class($methods) {
        $methods[] = 'WC_BiasPay_Gateway';
        return $methods;
    }

2. Proxy API Development

Purpose

The Proxy API ensures that communication between WooCommerce and BiasPay is secure and complies with domain restrictions.

Architecture

  1. Host: Subdomain pay.olympus-labs.com.
  2. Language: PHP (Laravel Framework for rapid development and scalability).
  3. Endpoints:
    • POST /api/process-payment:
      • Input: Order details (amount, currency, order ID, etc.).
      • Output: BiasPay response (transaction ID, status).
    • POST /api/payment-status:
      • Input: Transaction ID.
      • Output: Payment status (success, failure, or pending).

Flow

  1. WooCommerce plugin sends a request to /api/process-payment.
  2. The Proxy API validates the request (API key, parameters).
  3. The Proxy API forwards the request to BiasPay and returns the response to WooCommerce.
  4. If the WooCommerce plugin requests a payment status update, it queries /api/payment-status.

API Security

  • Use API keys for authentication.
  • Allowlist WooCommerce IPs or use a secret token in requests.
  • Use HTTPS for secure communication.

Proxy API Example Endpoints

Route: POST /api/process-payment

{
  "order_id": "12345",
  "amount": "100.00",
  "currency": "GBP",
  "customer_email": "[email protected]"
}

Response:

{
  "transaction_id": "txn_123abc",
  "status": "success"
}

Route: POST /api/payment-status

{
  "transaction_id": "txn_123abc"
}

Response:

{
  "status": "completed"
}

Proxy API Structure

  • Folder Name: proxy-api
  • Main Files:
    • routes/api.php: Define API routes.
    • app/Http/Controllers/PaymentController.php: Handles payment processing logic.
    • app/Services/BiasPayService.php: Handles BiasPay API communication.
    • tests/: For unit and integration tests.

3. API Documentation for WooCommerce Plugin

Base URL

https://pay.olympus-labs.com/api

Endpoints

  1. Process Payment

    • Method: POST

    • Endpoint: /api/process-payment

    • Headers:

      • Authorization: Bearer {API_KEY}
    • Body:

      {
        "order_id": "12345",
        "amount": "100.00",
        "currency": "GBP",
        "customer_email": "[email protected]"
      }
      
    • Response:

      {
        "transaction_id": "txn_123abc",
        "status": "success"
      }
      
  2. Check Payment Status

    • Method: POST

    • Endpoint: /api/payment-status

    • Headers:

      • Authorization: Bearer {API_KEY}
    • Body:

      {
        "transaction_id": "txn_123abc"
      }
      
    • Response:

      {
        "status": "completed"
      }
      

4. Development Steps

  1. Setup Development Environment:

    • Clone the WooCommerce site locally.
    • Set up a Laravel project on pay.olympus-labs.com.
  2. Develop WooCommerce Plugin:

    • Create the plugin structure.
    • Implement payment gateway registration.
    • Add configuration settings and checkout UI.
    • Implement API request logic and error handling.
  3. Develop Proxy API:

    • Set up Laravel with necessary middleware and routes.
    • Implement API endpoints for processing payments and checking statuses.
    • Add error handling, logging, and security measures.
  4. Testing:

    • Unit Tests:
      • Test WooCommerce plugin logic (order data handling, API calls).
      • Test Proxy API endpoints (input validation, BiasPay communication).
    • Integration Tests:
      • Test end-to-end flow (WooCommerce → Proxy API → BiasPay).
    • User Acceptance Testing:
      • Validate functionality in the staging environment.
  5. Deployment:

    • Deploy the Proxy API on pay.olympus-labs.com.
    • Install and configure the WooCommerce plugin on OlympusLabs.uk.

5. Maintenance and Monitoring

  1. Monitoring:

    • Set up API health monitoring tools (e.g., Pingdom, Postman Monitor).
    • Log all requests and responses for debugging purposes.
  2. Updates:

    • Update the plugin to stay compatible with WooCommerce and PHP versions.
    • Update Proxy API dependencies (e.g., Laravel) regularly.
  3. Support:

    • Provide documentation for troubleshooting common issues.
    • Offer support for plugin configuration.

Additional Requirement: Payment Form on pay.olympus-labs.com

When a user visits pay.olympus-labs.com directly, they should see a payment form with a list of products manually configured in the system. Users can select a product, fill in their details, and make a payment using BiasPay. Below are the details for implementing this feature.


1. Product Management

Admin Interface for Adding Products

  • Purpose: Allow the admin to add, edit, or remove products that will appear on the payment form.
  • Fields for Each Product:
    • Product Name (e.g., "Supplement 1, Supplement 2 etc").
    • Product Description (e.g., "supplement details").
    • Price (e.g., "100.00 USD").
    • Currency (default: USD).
    • Status (Active/Inactive).

Database Table for Products

  • Table Name: products

  • Columns:

    id (INT, AUTO_INCREMENT, PRIMARY KEY)
    name (VARCHAR(255), NOT NULL)
    description (TEXT, NULL)
    price (DECIMAL(10, 2), NOT NULL)
    currency (VARCHAR(10), DEFAULT 'GBP')
    status (ENUM('active', 'inactive'), DEFAULT 'active')
    created_at (TIMESTAMP)
    updated_at (TIMESTAMP)
    

Admin Product Management

  • Add a management panel in the Laravel backend (e.g., using Laravel Nova or custom admin pages).
  • Routes:
    • GET /admin/products: Display a list of products.
    • POST /admin/products: Add a new product.
    • PUT /admin/products/{id}: Update an existing product.
    • DELETE /admin/products/{id}: Remove a product.

2. Payment Form for Visitors

UI Design

  • Page URL: https://pay.olympus-labs.com
  • Elements:
    • List of products with their name, description, and price.
    • Form fields:
      • Product Selection: Dropdown or radio buttons to select a product.
      • Customer Information:
        • Name
        • Email
        • Phone (optional)
      • Payment Details: Payment handled via BiasPay integration.
    • Submit Button: "Pay Now".

Frontend Implementation

  • Frontend Framework: Use Blade templates (default Laravel templating engine).
  • Static Assets: Use TailwindCSS or Bootstrap for styling.
  • Form Validation: Validate required fields using Laravel's validation rules.

3. Backend Logic

Payment Form Submission

  • Route:
    • GET /: Display the payment form.
    • POST /process-payment: Handle form submission.
  • Controller Logic:
    • Validate input.
    • Generate an order with the selected product and customer details.
    • Send payment request to BiasPay via the existing /api/process-payment endpoint.
    • Return success or error message to the user.

Database Table for Orders

  • Table Name: manual_orders

  • Columns:

    id (INT, AUTO_INCREMENT, PRIMARY KEY)
    product_id (INT, FOREIGN KEY REFERENCES products(id))
    customer_name (VARCHAR(255), NOT NULL)
    customer_email (VARCHAR(255), NOT NULL)
    customer_phone (VARCHAR(20), NULL)
    transaction_id (VARCHAR(255), NULL)
    status (ENUM('pending', 'completed', 'failed'), DEFAULT 'pending')
    created_at (TIMESTAMP)
    updated_at (TIMESTAMP)
    

4. Payment Form Flow

  1. Visit Page:

    • User visits pay.olympus-labs.com and sees the list of products with a payment form.
  2. Select Product:

    • User selects a product and fills in their details.
  3. Submit Form:

    • Form is submitted to /process-payment.
  4. Validate and Process:

    • Backend validates input and creates an order record in manual_orders.
    • Calls the Proxy API /api/process-payment to initiate the payment with BiasPay.
    • Proxy API handles the BiasPay request and returns the result.
  5. Success or Failure:

    • On success: Update manual_orders status to completed, display a success message, and email the receipt to the customer.
    • On failure: Update status to failed and show an error message.

5. Example Code

Routes

use App\Http\Controllers\PaymentFormController;

Route::get('/', [PaymentFormController::class, 'showForm']);
Route::post('/process-payment', [PaymentFormController::class, 'processPayment']);

Controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\ManualOrder;

class PaymentFormController extends Controller
{
    public function showForm()
    {
        $products = Product::where('status', 'active')->get();
        return view('payment-form', compact('products'));
    }

    public function processPayment(Request $request)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'name' => 'required|string|max:255',
            'email' => 'required|email',
        ]);

        $product = Product::find($request->product_id);

        // Create a new order
        $order = ManualOrder::create([
            'product_id' => $product->id,
            'customer_name' => $request->name,
            'customer_email' => $request->email,
            'customer_phone' => $request->phone,
            'status' => 'pending',
        ]);

        // Prepare data for Proxy API
        $apiData = [
            'order_id' => $order->id,
            'amount' => $product->price,
            'currency' => $product->currency,
            'customer_email' => $request->email,
        ];

        // Send request to Proxy API
        $response = Http::post('https://pay.olympus-labs.com/api/process-payment', $apiData);

        if ($response->successful()) {
            $order->update([
                'transaction_id' => $response['transaction_id'],
                'status' => $response['status'],
            ]);
            return back()->with('success', 'Payment successful!');
        } else {
            $order->update(['status' => 'failed']);
            return back()->with('error', 'Payment failed. Please try again.');
        }
    }
}

Blade Template (resources/views/payment-form.blade.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Form</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css">
</head>
<body class="bg-gray-100">
    <div class="container mx-auto p-6">
        <h1 class="text-2xl font-bold mb-4">Pay for Products</h1>
        @if (session('success'))
            <div class="bg-green-500 text-white p-4 mb-4">
                {{ session('success') }}
            </div>
        @elseif (session('error'))
            <div class="bg-red-500 text-white p-4 mb-4">
                {{ session('error') }}
            </div>
        @endif
        <form action="/process-payment" method="POST">
            @csrf
            <div class="mb-4">
                <label for="product" class="block text-gray-700">Select Product:</label>
                <select name="product_id" id="product" class="block w-full p-2 border">
                    @foreach ($products as $product)
                        <option value="{{ $product->id }}">{{ $product->name }} - £{{ $product->price }}</option>
                    @endforeach
                </select>
            </div>
            <div class="mb-4">
                <label for="name" class="block text-gray-700">Your Name:</label>
                <input type="text" name="name" id="name" class="block w-full p-2 border">
            </div>
            <div class="mb-4">
                <label for="email" class="block text-gray-700">Your Email:</label>
                <input type="email" name="email" id="email" class="block w-full p-2 border">
            </div>
            <button type="submit" class="bg-blue-500 text-white py-2 px-4 rounded">Pay Now</button>
        </form>
    </div>
</body>
</html>

6. Testing

  • Test Scenarios:
    • Display all active products.
    • Validate input fields.
    • Ensure orders are created correctly.
    • Ensure successful payments update order statuses.
    • Handle failed payments gracefully.

This implementation ensures pay.olympus-labs.com becomes a versatile payment platform for both automated WooCommerce transactions and manual product payments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment