This directory contains comprehensive examples demonstrating real-world usage patterns of the Paystack PHP SDK. Each example is thoroughly documented with explanations, best practices, and production-ready code patterns.
- Quick Start
- Available Examples
- How to Run Examples
- Example Categories
- Testing Information
- Production Considerations
- PHP 8.1 or higher
- Composer (for dependency management)
- Paystack Account (sign up here)
- Test API Keys from your Paystack dashboard
-
Install the SDK:
composer require starfolksoftware/paystack-php
-
Get your API keys:
- Log into your Paystack Dashboard
- Navigate to Settings → API Keys & Webhooks
- Copy your Test Secret Key (starts with
sk_test_)
-
Update the examples:
- Replace
'sk_test_your_secret_key_here'with your actual test key - Never use live keys for testing!
- Replace
Perfect for: Developers migrating to v2.x, IDE optimization, better development experience
What you'll learn:
- Improved type hinting and IDE support in v2.x
- Direct method access vs magic property access
- Better autocomplete and intellisense features
- Backward compatibility with v1.x patterns
Key Features:
- ✅ Demonstrates all API endpoints with proper types
- ✅ Shows migration path from v1.x to v2.x
- ✅ Backward compatibility examples
- ✅ IDE benefits and developer experience improvements
php examples/improved_type_hinting_demo.phpPerfect for: Developers wanting structured, type-safe API responses
What you'll learn:
- Using response DTOs instead of generic arrays
- Accessing typed data with full IDE support
- Working with pagination and helper methods
- Converting between array and typed responses
- Backward compatibility strategies
Key Features:
- ✅ Customer, Transaction, and PaymentRequest DTOs
- ✅ Strongly-typed response objects with autocomplete
- ✅ Helper methods for common operations
- ✅ DateTimeImmutable for dates, structured data
- ✅ Pagination support with PaginationMeta
- ✅ Shows old vs new approach side-by-side
php examples/typed_responses_demo.phpPerfect for: First-time users, basic invoice creation, learning the fundamentals
What you'll learn:
- Creating payment requests with line items and taxes
- Handling API responses and error checking
- Retrieving and displaying payment request information
- Understanding the Paystack payment flow
Key Features:
- ✅ Comprehensive error handling
- ✅ Detailed response explanations
- ✅ Step-by-step process breakdown
- ✅ Production-ready code patterns
php examples/simple_payment_request.phpPerfect for: Developers who need comprehensive API coverage
What you'll learn:
- All payment request API methods and their parameters
- Advanced features like drafts, finalization, and archiving
- Payment verification and status monitoring
- Notification management and customer communication
Key Features:
- ✅ Complete API method coverage
- ✅ Advanced parameter usage
- ✅ Real-world error scenarios
- ✅ Best practice implementations
php examples/payment_request_demo.phpPerfect for: Service providers, freelancers, B2B businesses
What you'll learn:
- Complete invoice lifecycle management
- Customer profile management and updates
- Progressive billing (adding items over time)
- Professional invoice formatting and presentation
- Payment monitoring and follow-up processes
Key Features:
- ✅ End-to-end invoice workflow
- ✅ Customer management integration
- ✅ Automated notification systems
- ✅ Revenue tracking and analytics
- ✅ Professional formatting and presentation
php examples/invoice_workflow.phpPerfect for: SaaS platforms, subscription services, membership sites
What you'll learn:
- Multi-tier subscription management
- Automated billing cycle processing
- Failed payment recovery strategies
- Subscription upgrades and downgrades
- Revenue analytics and reporting
- Customer retention management
Key Features:
- ✅ Comprehensive subscription management
- ✅ Automated billing processes
- ✅ Advanced analytics and reporting
- ✅ Failed payment recovery systems
- ✅ Multi-tier pricing strategies
- ✅ Production-ready automation
php examples/recurring_billing.phpimproved_type_hinting_demo.php- v2.x type safety features (Phase 1)typed_responses_demo.php- Response DTOs (Phase 2)simple_payment_request.php- Basic payment request creation- Individual API method demonstrations
payment_request_demo.php- Complete API coverageinvoice_workflow.php- Business workflow implementation
recurring_billing.php- Complex subscription management- Production-ready automation systems
- Simple product payments
- Shopping cart integration
- Order management workflows
- Invoice generation and management
- Project-based billing
- Time-based service charging
- Recurring billing automation
- Subscription tier management
- Usage-based billing
- Split payment scenarios
- Multi-vendor management
- Commission handling
# Run from the project root directory
php examples/improved_type_hinting_demo.php
php examples/typed_responses_demo.php
php examples/simple_payment_request.php
php examples/invoice_workflow.php
php examples/recurring_billing.php
php examples/payment_request_demo.php# Create a test script
cp examples/simple_payment_request.php my_test.php
# Edit my_test.php with your API key
php my_test.php# Include in your application
require_once 'vendor/autoload.php';
require_once 'examples/payment_functions.php';Safe Testing: All examples use test mode by default
- No real money transactions
- Safe for experimentation
- Full API feature access
Test Credentials:
// Test Secret Key (replace with yours)
$secretKey = 'sk_test_your_actual_test_key_here';
// Test Card Numbers for Different Scenarios
$testCards = [
'successful_payment' => '4084084084084081',
'insufficient_funds' => '4084084084084107',
'invalid_pin' => '4084084084084099',
'timeout' => '4084084084084016'
];Paystack Dashboard:
- Monitor all test transactions in real-time
- View detailed payment logs and analytics
- Test webhook configurations
Debug Output:
- All examples include comprehensive logging
- Clear success/error indicators
- Detailed API response information
API Key Management:
// ✅ Good: Environment variables
$secretKey = $_ENV['PAYSTACK_SECRET_KEY'];
// ❌ Bad: Hardcoded keys
$secretKey = 'sk_test_actual_key_here';Error Handling:
- Implement comprehensive try-catch blocks
- Log errors for debugging and monitoring
- Provide user-friendly error messages
- Handle network timeouts and retries
Connection Management:
- Reuse HTTP connections when possible
- Implement connection pooling for high-volume applications
- Use appropriate timeout settings
Caching Strategies:
- Cache frequently accessed data (banks, plans)
- Implement smart cache invalidation
- Use Redis or Memcached for distributed caching
Webhook Implementation:
- Set up real-time payment notifications
- Implement signature verification
- Handle duplicate events gracefully
Analytics and Reporting:
- Track payment success rates
- Monitor customer behavior patterns
- Generate business intelligence reports
Laravel:
// Service Provider integration
// Controller method examples
// Eloquent model relationshipsSymfony:
// Service container configuration
// Event system integration
// Doctrine entity examplesCodeIgniter:
// Library integration
// Controller patterns
// Database integrationCustomer Management:
-- Customer table structure
-- Payment history tracking
-- Subscription managementTransaction Logging:
-- Transaction records
-- Audit trails
-- Reconciliation support- Getting Started Guide - Complete setup and first payment
- API Reference - Detailed method documentation
- Advanced Usage - Complex patterns and optimizations
- Troubleshooting Guide - Common issues and solutions
After exploring these examples:
- Choose your use case - Pick the example closest to your needs
- Customize the code - Adapt the examples to your specific requirements
- Implement webhooks - Set up real-time payment notifications
- Test thoroughly - Use test cards and monitor the dashboard
- Go live - Switch to live API keys for production
E-commerce Integration:
- Start with
simple_payment_request.php - Implement customer management
- Add order tracking and fulfillment
- Set up automated receipts and notifications
SaaS Subscription Service:
- Study
recurring_billing.phpthoroughly - Implement subscription management portal
- Set up automated billing cycles
- Add usage tracking and billing
- Implement dunning management for failed payments
Service-Based Business:
- Begin with
invoice_workflow.php - Customize invoice templates and branding
- Integrate with project management systems
- Automate follow-up and reminder systems
- Set up accounting system integration
- Start small - Begin with basic examples and gradually add complexity
- Test extensively - Use all available test scenarios before going live
- Monitor actively - Set up comprehensive logging and monitoring
- Follow best practices - Implement security, error handling, and performance optimizations
- Stay updated - Follow the repository for updates and new features
Happy coding! 🚀
For additional help, check out our troubleshooting guide or open an issue on GitHub.