Skip to content

Latest commit

History

10 Commits

Folders and files

NameName
Last commit message
Last commit date

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

importcom.recceda.payfast.PayFastService;
importcom.recceda.payfast.config.PayFastConfig;
// Sandbox configurationPayFastConfigconfig = newPayFastConfig(
"10000100", // merchant ID"46f0cd694581a", // merchant key null, // passphrase (optional)true// sandbox mode
);
PayFastServiceservice = newPayFastService(config);

2. One-off Payment

importcom.recceda.payfast.model.PaymentRequest;
importcom.recceda.payfast.model.PayFastFormData;
importjava.math.BigDecimal;
### 2.One-offPayment
```javaimportcom.recceda.payfast.model.PaymentRequest;
importcom.recceda.payfast.model.PayFastResponse;
importjava.math.BigDecimal;
PaymentRequestpayment = newPaymentRequest();
payment.setAmount(newBigDecimal("100.00"));
payment.setItemName("Demo Product");
payment.setItemDescription("Product description");
payment.setMPaymentId("ORDER-" + System.currentTimeMillis());
// Optional: Set return URLspayment.setReturnUrl("https://yoursite.com/return");
payment.setCancelUrl("https://yoursite.com/cancel");
payment.setNotifyUrl("https://yoursite.com/notify");
// Optional: Set buyer informationpayment.setNameFirst("John");
payment.setNameLast("Doe");
payment.setEmailAddress("john.doe@example.com");
// Create payment form data with all fields and signaturePayFastFormDataformData = 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:

importcom.recceda.payfast.exception.*;
try {
PayFastFormDataformData = service.createPaymentFormData(payment);
} catch (ConfigurationExceptione) {
// Invalid configuration (missing merchant ID/key)log.error("Configuration error: {}", e.getMessage());
} catch (ValidationExceptione) {
// Invalid request data (missing required fields, invalid amounts, etc.)log.error("Validation error: {}", e.getMessage());
} catch (SignatureExceptione) {
// Signature generation or validation errorslog.error("Signature error: {}", e.getMessage());
} catch (HttpExceptione) {
// HTTP communication errorslog.error("HTTP error: {}", e.getMessage());
} catch (PayFastExceptione) {
// Base exception for all other PayFast operationslog.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:
    PayFastConfigconfig = newPayFastConfig(
    "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

11 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages