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
- 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
Add to your pom.xml:
<dependency>
<groupId>com.recceda</groupId>
<artifactId>payfast-java-sdk</artifactId>
<version>1.0.7</version>
</dependency>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);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);
### 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
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());
}1- Daily2- Weekly3- Monthly4- Quarterly5- Biannually6- Annual
- Go to PayFast Sandbox
- Register for a free sandbox account with your email
- Login to your sandbox dashboard
- Navigate to Settings → Merchant Details to get your unique:
- Merchant ID
- Merchant Key
- Set a Salt Passphrase in Settings → Account 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
This SDK implements PayFast's signature generation algorithm with:
- Python-compatible URL encoding using
urllib.parse.quote_plusequivalent - Proper parameter ordering matching PayFast's official Python implementation
- Spaces encoded as '+' (not '%20') per PayFast requirements
- Uppercase hex encoding for special characters
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
Run the comprehensive test suite:
mvn testThe 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
- Java 8+
- Maven 3.6+
- SLF4J for logging
For production use:
- Get real credentials from PayFast merchant portal
- Set sandbox to false:
PayFastConfigconfig = newPayFastConfig( "your-merchant-id", "your-merchant-key", "your-passphrase", false// production mode );
- Configure proper return URLs for your domain
- Use HTTPS for all URLs
- PayFast Documentation: https://developers.payfast.co.za/
- PayFast Support: https://www.payfast.co.za/support/
Mike Chiloane Email: mike@mikechiloane.co.za
MIT License - see LICENSE file for details
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
