# AhaPay WordPress Plugin - Technical Documentation and User Manual

## Table of Contents
1. [Overview](#1-overview)
2. [Plugin Architecture](#2-plugin-architecture)
3. [Installation and Setup](#3-installation-and-setup)
4. [Core Components](#4-core-components)
5. [Code Structure Analysis](#5-code-structure-analysis)
6. [Configuration Guide](#6-configuration-guide)
7. [Features and Functionality](#7-features-and-functionality)
8. [Security Features](#8-security-features)
9. [Quick Reference](#9-quick-reference)
10. [Development Guide](#10-development-guide)
11. [API Integration](#11-api-integration)
12. [Troubleshooting](#12-troubleshooting)
13. [Packaging the Plugin for Distribution](#13-packaging-the-plugin-for-distribution)

---

## 1. Overview

### What is AhaPay?
AhaPay is a Buy Now Pay Later (BNPL) payment gateway plugin for WordPress/WooCommerce that allows customers to split their purchases into 4 or 7 installments with 0% interest for the 4-payment plan.

### Key Features
- **Split Payments**: Automatic division into 4 or 7 installments
- **Zero Interest**: 0% interest rate for 4-payment plans
- **WooCommerce Integration**: Seamless integration with WooCommerce
- **Block Editor Support**: Compatible with WordPress block editor
- **Mobile Responsive**: Optimized for mobile devices
- **Real-time Status**: Live order status checking
- **Refund Support**: Built-in refund functionality

---

## 2. Plugin Architecture

### File Structure
```ahapay-plugin/
├── payment-gateway.php # Main plugin file
├── README.md          # Plugin description
├── includes/           # Core PHP classes
│   ├── class-ahapay-gateway.php
│   ├── class-ahapay-callback-handler.php
│   ├── class-ahapay-status-handler.php
│   └── class-ahapay-payments-blocks.php
├── assets/             # Frontend assets
│   ├── css/            # Stylesheets
│   ├── js/             # JavaScript files
│   ├── img/            # Images and icons
│   └── blocks/         # Block complied files
├── blocks/             # Gutenberg blocks
│   └── build/          # block uncompiled files
├── package.json        # Node.js dependencies
└── webpack.config.js   # Webpack configuration
```
### Technology Stack
- **Backend**: PHP 7.4+, WordPress, WooCommerce
- **Frontend**: JavaScript ES6+, CSS3, HTML5
- **Build Tools**: Webpack, @wordpress/scripts
- **Package Manager**: npm

---

## 3. Installation and Setup

#### 1. Pre-Installation Checklist
- [ ] WordPress 5.4+ installed
- [ ] WooCommerce 4.8+ active
- [ ] PHP 7.4+ with OpenSSL extension
- [ ] SSL certificate installed (production)
- [ ] Currency set to MYR

#### 2. AhaPay Account Setup
1. Register at AhaPay as merchant
2. Obtain API credentials (Test & Live)

#### 3. Plugin Installation´

##### A. Manual Installation
1. Download the plugin ZIP file from the official source.
2. Extract the ZIP file on your computer.
3. Upload the extracted `ahapay-plugin` folder to your server at `/wp-content/plugins/ahapay/` using FTP or your hosting file manager.
4. Go to your WordPress admin dashboard, navigate to **Plugins > Installed Plugins**, and activate **AhaPay**.
5. Proceed to WooCommerce > Settings > Payments > AhaPay to configure your API credentials and test the connection.

##### B. Installation via WordPress Admin UI
1. In your WordPress admin dashboard, go to **Plugins > Add New**. 
![Add Plugin Menu](assets/img/add-plugin-menu.png)
2. Click **Upload Plugin** at the top of the page. 
![Upload Plugin](assets/img/upload-plugin.png)
![Click Upload](assets/img/click-upload.png)
3. Select the plugin ZIP file and click **Install Now**.
![Select Zip](assets/img/select.png)
![Install](assets/img/install.png)
4. Once installed, click **Activate Plugin**.
![Activate](assets/img/activate.png)
5. Click Settings or Navigate to WooCommerce > Settings > Payments > AhaPay to enter your API credentials and test the connection.
![Setting](assets/img/setting.png)
![Setting Page](assets/img/setting-page.png)


### Initial Configuration
1. **Environment Setup**: Choose between Sandbox and Live environment
2. **API Credentials**: Enter merchant credentials
3. **Currency**: Ensure MYR (Malaysian Ringgit) is selected
4. **Pages**: Configure success and error pages
5. **Labels**: Customize product labels and colors

---

## 4. Core Components

### 4.1 Main Plugin File (`payment-gateway.php`)

This is the entry point of the plugin containing:

#### Security Checks
```php 
if (!defined('ABSPATH')) { exit; }
```
Prevents direct access to the file.

```php 
define('AHAPAY_VERSION', '1.0.0'); define('AHAPAYBUYNOWPAYLATER_LIVE_BASE_URL', "[https://api.ahapay.com/](https://api.ahapay.com/)"); define('AHAPAYBUYNOWPAYLATER_SANDBOX_BASE_URL', "[https://api.bnpl-my.dev.mychili.id](https://api.bnpl-my.dev.mychili.id)");
```
Defines important constants for API endpoints and plugin version.

#### Hook Registration
The plugin registers multiple WordPress hooks:
- Payment gateway registration
- Asset enqueuing
- AJAX handlers
- Block integration
- Admin interfaces

### 4.2 Gateway Class (`class-ahapay-gateway.php`)
The main payment gateway class extending `WC_Payment_Gateway`:

#### Key Properties
- `$debug`: Debug mode setting
- `$environment`: Sandbox/Live environment
- `$api_status`: Current API connection status
- `$logger`: WordPress logger instance

#### Core Methods
- `__construct()`: Initializes the gateway
- `init_form_fields()`: Defines admin settings
- `process_payment()`: Handles payment processing
- `is_available()`: Checks if gateway is available

### 4.3 Status Handler (`class-ahapay-status-handler.php`)

Manages payment status updates from AhaPay API:

#### Status Mapping
- `PAYMENT_SUCCESSFUL` → WooCommerce `completed`
- `CANCELLED` → WooCommerce `cancelled`
- `UNAVAILABLE` → WooCommerce `failed`
- `PAYMENT_IN_PROGRESS` → WooCommerce `on-hold`
- `REFUNDED` → WooCommerce `refunded`


### 4.4 Callback Handler (`class-ahapay-callback-handler.php`)

Processes webhook callbacks from AhaPay:
- Validates incoming requests
- Processes payment notifications
- Updates order status
- Logs transactions

---

## 5. Code Structure Analysis

### 5.1 Frontend Assets

#### CSS Files
1. **`ahapay-label.css`**: Product label styling
    - Bottom banner positioning
    - Responsive design
    - Customizable colors

2. **`ahapaybuynowpaylater-block-style.css`**: Block editor styling
    - Card layout
    - Progress indicators
    - Timeline visualization

3. **`modal.css`**: Modal popup styling
    - Responsive modal design
    - Payment button styling
    - Mobile optimization

#### JavaScript Files
1. **`ahapaybuynowpaylater-admin-api.js`**: Admin Status Checking
   The plugin provides manual status checking through:
   - Admin order page buttons
   - AJAX API calls (`ahapay_handle_api_call`)
   - Real-time status updates in admin interface

2. **Block Integration**: React-based blocks for Gutenberg editor
    - Custom block registration
    - Dynamic content rendering
    - Responsive design
3. **`modal.js`**: Modal functionality
    - Open/close modal actions
    - Payment process steps
    - Custom event handling
4. **`ahapay-minimum-check.js`**: Minimum order amount validation
    - Prevents checkout if below threshold
    - Displays error messages

### 5.2 PHP Class Structure

#### Inheritance Hierarchy

```
WC_Payment_Gateway (WooCommerce) 
└── Ahapaybuynowpaylater_WC_Gateway (Main gateway class)

Independent Classes: 
├── AhaPay_Status_Handler
├── AhaPay_Callback_Handler
└── Ahapaybuynowpaylater_WC_Blocks_Support
``` 
#### Design Patterns Used
- **Singleton Pattern**: For main gateway instance
- **Factory Pattern**: For creating API requests
- **Observer Pattern**: For status change notifications
- **Strategy Pattern**: For different payment environments


---

## 6. Configuration Guide

### 6.1 Admin Settings

#### Basic Settings
- **Enable/Disable**: Toggle plugin activation
- **Title**: Display name on checkout
- **Description**: Payment method description
- **Environment**: Sandbox or Live mode

#### Advanced Settings
- **Debug Mode**: Enable detailed logging
- **API Status**: Connection status indicator
- **Product Labels**: Enable/disable product badges
- **Custom Colors**: Label background and text colors

#### Page Configuration
- **Success Page**: Post-payment success redirect
- **Error Page**: Payment failure redirect

### 6.2 Product Display Options

#### Label Positioning
- Top banner on product images
- Bottom banner on product cards
- Customizable text and colors

#### Modal Information
- Product page popup with payment details
- Step-by-step payment process
- Terms and conditions links
### Step-by-Step Configuration
1. **API Credentials Setup**
   - Obtain API key from AhaPay merchant portal
   - Enter key in WooCommerce > Settings > Payments > AhaPay
   - Verify connection status (should show "Verified" green indicator)

2. **Environment Configuration**
   - Select "Test" for development/testing
   - Select "Production" for live transactions
   - Note: Different API endpoints are used for each environment

3. **Product Display Options**
   - Enable product labels for visual marketing
   - Customize label text and colors
   - Configure product page payment information


---

## 7. Features and Functionality

### 7.1 Payment Processing Flow

1. **Customer Selection**: Customer chooses AhaPay at checkout
2. **Order Creation**: WordPress creates pending order
3. **API Request**: Plugin sends payment request to AhaPay
4. **Redirect**: Customer redirected to AhaPay portal
5. **Payment**: Customer completes payment setup
6. **Callback**: AhaPay sends status updates
7. **Order Update**: WordPress updates order status

### 7.2 Status Monitoring

#### Admin Interface
- Manual status check buttons
- Order detail enhancements
- Transaction log viewing
```php
ahapay_handle_api_call()
```

### 7.3 Block Editor Integration

#### Gutenberg Compatibility
- Custom payment blocks
- Visual payment method display
- Responsive block designs

#### Block Features
- Logo integration
- Progress indicators
- Timeline visualization
- Customizable layouts

---
## Security Features
### API Key Encryption
- Automatic encryption using AES-256-CBC
- Secure key storage and retrieval
- Secret key generation on activation

### Webhook Security
- Signature validation for callbacks
- HTTPS requirement for production
- Callback URL configuration

## Business Rules
### Minimum Order Amount
- Required minimum: 55 MYR
- Automatic validation at checkout
- Error handling for insufficient amounts

### Currency Support
- Supported currency: Malaysian Ringgit (MYR)
- Automatic availability checking
- Configuration requirements

---

## 9. Quick Reference
### 9.1 Essential Settings Checklist
- [ ] Currency set to MYR
- [ ] API key entered and verified (green status)
- [ ] Environment selected (Test/Production)
- [ ] Success/Error pages configured
- [ ] SSL certificate installed (production)
- [ ] Webhook URL accessible

### 9.2 Key URLs & Endpoints
- Sandbox API: `https://api.bnpl-my.dev.mychili.id`
- Production API: `https://api.ahapay.my`
- Webhook endpoint: `your-site.com/wp-json/ahapaybuynowpaylater/v1/callback`


## 10. Development Guide

### 10.1 Environment Setup

#### Requirements
```bash 
npm install
```
#### Build Process Compiles JavaScript and CSS assets
```bash 
npx webpack --config webpack.config.js  
```
#### Webpack Configuration
The plugin uses `@wordpress/scripts` for building:
- ES6+ JavaScript compilation
- CSS preprocessing
- Asset optimization
- Hot reloading in development


### 10.2 Extending the Plugin

#### Adding New Payment Methods
1. Extend the gateway class
2. Implement required methods
3. Register with WooCommerce
4. Add frontend assets

#### Status Handlers
```php 
class Custom_Status_Handler extends AhaPay_Status_Handler { public function handle_custom_status(order,status) { // Custom logic here } }
```

#### Frontend Customization
- Override CSS variables
- Add custom JavaScript events
- Extend modal functionality
- Create custom blocks

### 10.3 API Integration

#### Endpoint Structure
```Base 
URL: AHAPAYBUYNOWPAYLATER_LIVE_BASE_URL or AHAPAYBUYNOWPAYLATER_SANDBOX_BASE_URL Endpoints: POST /transactions # Create payment GET /transactions/{id} # Check status POST /refunds # Process refund
```

#### Request Format
```php 
request_data = [ 'amount' =>order->get_total(), 'currency' => 'MYR', 'merchant_id' => this->merchant_id, 'order_id' =>order->get_id(), 'callback_url' => $callback_url ];
```

#### Response Handling
```php 
if (response['success']) {redirect_url = response['redirect_url']; return [ 'result' => 'success', 'redirect' =>redirect_url ]; }
``` 

---
## 11. API Integration

### 11.1 Authentication

#### API Keys
- API keys are required for both Sandbox and Production environments
- Environment selection

#### Security
- HTTPS required
- Request signing
- Callback verification

### 11.2 Webhook Handling

#### Callback Validation
```php 
received_signature =_SERVER['HTTP_SIGNATURE']; calculated_signature = hash_hmac('sha256',payload, $secret_key);
if (!hash_equals(received_signature,calculated_signature)) { throw new Exception('Invalid signature'); }
``` 

#### Status Processing
The callback handler processes various payment statuses and updates orders accordingly.

---

## 12. Troubleshooting

### 12.1 Common Issues

#### Gateway Not Available
- **Cause:** Currency not MYR
- **Solution:** WooCommerce > Settings > General > Currency Options
- **Cause:** API key not set or invalid
- **Solution:** WooCommerce > Settings > Payments > AhaPay > API Key

#### API Connection Failed
- **Symptoms:** Red status indicator
- **Check:** Network connectivity, API key validity


#### API Key Not Verified
- Check API key format and validity
- Verify network connectivity to AhaPay servers
- Review error logs in WooCommerce > Status > Logs

#### Minimum Order Amount Issues
- Ensure cart total exceeds 55 MYR
- Check for tax and shipping inclusions
- Verify currency is set to MYR

#### Payment Not Processing
- Check API credentials
- Verify environment settings
- Review error logs
- Test API connectivity

#### Status Updates Not Working
- Verify callback URL accessibility
- Check webhook configuration
- Review server logs
- Test network connectivity

#### Frontend Display Issues
- Clear cache
- Check CSS conflicts
- Verify JavaScript errors
- Test browser compatibility

### 12.2 Debug Mode

#### Enabling Debug Logging
1. Go to WooCommerce > Settings > Payments > AhaPay
2. Enable "Debug Mode"
3. Check logs in WooCommerce > Status > Logs

#### Log Analysis
```php 
this->log('API Request: ' . json_encode(request_data), 'info'); this->log('API Response: ' . json_encode(response), 'info'); this->log('Error occurred: ' .error_message, 'error');
```

### 12.4 Performance Optimization

#### Caching Considerations
- Exclude dynamic pages from caching
- Cache static assets
- Optimize database queries

#### Asset Optimization
- Minify CSS and JavaScript
- Optimize images
- Use CDN for static assets



## 13. Packaging the Plugin for Distribution

When preparing the AhaPay plugin for delivery to a client or for publishing in a public API repository, ensure your ZIP archive includes only the necessary files and folders required for installation and operation. Exclude development files, local configuration, and any sensitive or unnecessary content.

### Required Files and Folders
Include the following in your ZIP package:

- `payment-gateway.php` (Main plugin file)
- `README.md` (Plugin description and documentation)
- `includes/` (All PHP classes)
- `assets/` (All CSS, JS, images, and block assets)


### Exclude from ZIP
Do **not** include:
- `node_modules/` (local dependencies)
- `blocks/` (Gutenberg block build files)
- `webpack.config.js` (For reference, if needed)
- `package.json` (For reference, if needed)
- Local configuration files, build scripts, or any sensitive data

### Example Directory Structure for ZIP
```
ahapay-plugin/
├── payment-gateway.php
├── README.md
├── includes/
├── assets/
```

Compress the above structure into a single ZIP file (e.g., `ahapay-plugin.zip`) before providing it to the client or publishing it publicly.


---

## Conclusion

This documentation provides a comprehensive guide to understanding, implementing, and maintaining the AhaPay WordPress plugin. The modular architecture allows for easy customization and extension while maintaining compatibility with WordPress and WooCommerce standards.

For additional support or advanced customization requirements, refer to the WordPress and WooCommerce documentation or contact the development team.

---

**Document Version**: 1.0  
**Last Updated**: 2025-06-07  
**WordPress Version**: 5.4+  
**WooCommerce Version**: 4.8+  
**PHP Version**: 7.4+