Skip to content

A comprehensive Java SDK for PayFast payment gateway integration with proper signature validation and PayFast-compliant URL encoding.

Notifications You must be signed in to change notification settings

mikechiloane/payfast-java-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PayFast Java SDK

PayFast SDK Logo

A comprehensive Java SDK for PayFast payment gateway integration with proper signature validation and PayFast-compliant URL encoding.

Developer: Mike Chiloane
Email: mike@mikechiloane.co.za

Features

  • One-off payments - Single payment transactions
  • Automatic signature generation - Python-compatible URL encoding
  • Sandbox/Production modes - Easy environment switching
  • Comprehensive error handling - Specific exceptions for different scenarios
  • Full PayFast compliance - Matches official implementation

Installation

Add to your pom.xml:

<dependency>
    <groupId>com.recceda</groupId>
    <artifactId>payfast-java-sdk</artifactId>
    <version>1.0.7</version>
</dependency>

Quick Start

1. Basic Setup

import com.recceda.payfast.PayFastService;
import com.recceda.payfast.config.PayFastConfig;

// Sandbox configuration
PayFastConfig config = new PayFastConfig(
    "10000100",           // merchant ID
    "46f0cd694581a",      // merchant key  
    null,                 // passphrase (optional)
    true                  // sandbox mode
);

PayFastService service = new PayFastService(config);

2. One-off Payment

import com.recceda.payfast.model.PaymentRequest;
import com.recceda.payfast.model.PayFastFormData;
import java.math.BigDecimal;

### 2. One-off Payment
```java
import com.recceda.payfast.model.PaymentRequest;
import com.recceda.payfast.model.PayFastResponse;
import java.math.BigDecimal;

PaymentRequest payment = new PaymentRequest();
payment.setAmount(new BigDecimal("100.00"));
payment.setItemName("Demo Product");
payment.setItemDescription("Product description");
payment.setMPaymentId("ORDER-" + System.currentTimeMillis());

// Optional: Set return URLs
payment.setReturnUrl("https://yoursite.com/return");
payment.setCancelUrl("https://yoursite.com/cancel");
payment.setNotifyUrl("https://yoursite.com/notify");

// Optional: Set buyer information
payment.setNameFirst("John");
payment.setNameLast("Doe");
payment.setEmailAddress("john.doe@example.com");

// Create payment form data with all fields and signature
PayFastFormData formData = service.createPaymentFormData(payment);

Demo Application


### 3. Subscription Payment
```java
import com.recceda.payfast.model.SubscriptionRequest;

SubscriptionRequest subscription = new SubscriptionRequest();
subscription.setAmount(new BigDecimal("50.00"));           // Initial amount
subscription.setItemName("Monthly Subscription");
subscription.setItemDescription("Premium service subscription");
subscription.setMPaymentId("SUB-" + System.currentTimeMillis());

// Subscription specific settings
subscription.setSubscriptionType("1");                     // Subscription
subscription.setRecurringAmount(5000);                     // 50.00 in cents
subscription.setFrequency(3);                             // Monthly (1=Daily, 2=Weekly, 3=Monthly, 4=Quarterly, 5=Biannually, 6=Annual)
subscription.setCycles(12);                               // 12 months (0 = infinite)

// Create subscription form data with all fields and signature
PayFastFormData formData = service.createSubscriptionFormData(subscription);



## Demo Application

Run the included demo to see the SDK in action:

```bash
mvn exec:java -Dexec.mainClass="com.recceda.App"

This will:

  • Create a sample payment form
  • Create a sample subscription form
  • Display PayFast sandbox URLs for testing

Error Handling

The SDK provides comprehensive error handling with specific exceptions:

import com.recceda.payfast.exception.*;

try {
    PayFastFormData formData = service.createPaymentFormData(payment);
} catch (ConfigurationException e) {
    // Invalid configuration (missing merchant ID/key)
    log.error("Configuration error: {}", e.getMessage());
} catch (ValidationException e) {
    // Invalid request data (missing required fields, invalid amounts, etc.)
    log.error("Validation error: {}", e.getMessage());
} catch (SignatureException e) {
    // Signature generation or validation errors
    log.error("Signature error: {}", e.getMessage());
} catch (HttpException e) {
    // HTTP communication errors
    log.error("HTTP error: {}", e.getMessage());
} catch (PayFastException e) {
    // Base exception for all other PayFast operations
    log.error("PayFast error: {}", e.getMessage());
}

Configuration Options

PayFast Frequency Values

  • 1 - Daily
  • 2 - Weekly
  • 3 - Monthly
  • 4 - Quarterly
  • 5 - Biannually
  • 6 - Annual

Generate Your Own Sandbox Credentials

  1. Go to PayFast Sandbox
  2. Register for a free sandbox account with your email
  3. Login to your sandbox dashboard
  4. Navigate to SettingsMerchant Details to get your unique:
    • Merchant ID
    • Merchant Key
  5. Set a Salt Passphrase in SettingsAccount Information (required for subscriptions)

Benefits of your own sandbox account:

  • Test subscriptions with proper passphrase
  • View transaction history and ITN logs
  • Test subscription management features
  • More realistic testing environment

Technical Implementation

Signature Generation

This SDK implements PayFast's signature generation algorithm with:

  • Python-compatible URL encoding using urllib.parse.quote_plus equivalent
  • Proper parameter ordering matching PayFast's official Python implementation
  • Spaces encoded as '+' (not '%20') per PayFast requirements
  • Uppercase hex encoding for special characters

HTML Form Generation

The SDK automatically generates HTML payment forms that:

  • Include all required PayFast parameters
  • Have proper signatures for validation
  • Auto-submit via JavaScript (optional)
  • Save to descriptive filenames for debugging

Testing

Run the comprehensive test suite:

mvn test

The SDK includes:

  • 146 test cases covering all functionality
  • Unit tests for all components
  • Integration tests with real PayFast examples
  • Signature validation tests
  • Error handling tests

Requirements

  • Java 8+
  • Maven 3.6+
  • SLF4J for logging

Production Setup

For production use:

  1. Get real credentials from PayFast merchant portal
  2. Set sandbox to false:
    PayFastConfig config = new PayFastConfig(
        "your-merchant-id",
        "your-merchant-key", 
        "your-passphrase",
        false  // production mode
    );
  3. Configure proper return URLs for your domain
  4. Use HTTPS for all URLs

Support

Author

Mike Chiloane Email: mike@mikechiloane.co.za

License

MIT License - see LICENSE file for details

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

About

A comprehensive Java SDK for PayFast payment gateway integration with proper signature validation and PayFast-compliant URL encoding.

Topics

Resources

Stars

Watchers

Forks

Packages

 
 
 

Languages