https://github.com/mikechiloane/payfast-java-sdk
A comprehensive Java SDK for PayFast payment gateway integration with proper signature validation and PayFast-compliant URL encoding.
https://github.com/mikechiloane/payfast-java-sdk
java payfast payments sdk
Last synced: about 1 month ago
JSON representation
A comprehensive Java SDK for PayFast payment gateway integration with proper signature validation and PayFast-compliant URL encoding.
- Host: GitHub
- URL: https://github.com/mikechiloane/payfast-java-sdk
- Owner: mikechiloane
- Created: 2025-08-03T13:52:04.000Z (11 months ago)
- Default Branch: main
- Last Pushed: 2025-08-10T20:53:16.000Z (10 months ago)
- Last Synced: 2025-08-10T22:23:00.111Z (10 months ago)
- Topics: java, payfast, payments, sdk
- Language: Java
- Homepage:
- Size: 92.8 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# PayFast Java SDK

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`:
```xml
com.recceda
payfast-java-sdk
1.0.7
```
## Quick Start
### 1. Basic Setup
```java
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
```java
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:
```java
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](https://sandbox.payfast.co.za)
2. Register for a free sandbox account with your email
3. Login to your sandbox dashboard
4. Navigate to **Settings** → **Merchant Details** to get your unique:
- Merchant ID
- Merchant Key
5. 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
## 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:
```bash
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**:
```java
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
- **PayFast Documentation**: https://developers.payfast.co.za/
- **PayFast Support**: https://www.payfast.co.za/support/
## Author
**Mike Chiloane**
Email: [mike@mikechiloane.co.za](mailto: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