PHP code example of tshimologomoeng / payfast-php

1. Go to this page and download the library: Download tshimologomoeng/payfast-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tshimologomoeng / payfast-php example snippets




shimologoMoeng\Payfast\SimpleIntegration\PayfastSimpleIntegration;
use TshimologoMoeng\Payfast\Enums\PaymentMethod;

// Initialize PayFast
$payfast = new PayfastSimpleIntegration(
    merchant_id: 'your_merchant_id',
    merchant_key: 'your_merchant_key',
    testing_mode: true, // Set to false for production
    passphrase: 'your_passphrase', // Optional
);

// Set customer details (optional)
$payfast->set_customer_details(
    name_first: 'John',
    name_last: 'Doe',
    email_address: '[email protected]',
    cell_number: '0821234567' // Optional
);

// Set transaction details
$payfast->set_transaction_details(
    amount: 100.00,
    item_name: 'Product Name',
    return_url: 'yourdomain.co.za/../success',
    cancel_url: 'yourdomain.co.za/../cancel',
    notify_url: 'yourdomain.co.za/../notify',
    item_description: 'Product description',
    m_payment_id: 'ORDER-123', // Your unique order ID
    payment_method: PaymentMethod::Credit_Card// Optional: force specific payment method
);

// Redirect user to PayFast
$paymentUrl = $payfast->get_payment_url();
header("Location: $paymentUrl");
exit;



use TshimologoMoeng\Payfast\OnsitePayment\PayfastOnsitePayment;

$payfast = new PayfastOnsitePayment(
    merchant_id: 'your_merchant_id',
    merchant_key: 'your_merchant_key',
    testing_mode: true,
    passphrase: 'your_passphrase'
);

$data = [
    'merchant_id' => 'your_merchant_id',
    'merchant_key' => 'your_merchant_key',
    'amount' => 100.00,
    'item_name' => 'Product Name',
    'return_url' => 'https://yoursite.com/success',
    'cancel_url' => 'https://yoursite.com/cancel',
    'notify_url' => 'https://yoursite.com/webhook'
];

// Generate payment identifier (UUID)
$uuid = $payfast->setup_onsite_payment($data);



use TshimologoMoeng\Payfast\RecurringBilling\PayfastSubscription;
use TshimologoMoeng\Payfast\Enums\SubscriptionFrequency;

$subscription = new PayfastSubscription(
    merchant_id: 'your_merchant_id',
    merchant_key: 'your_merchant_key',
    testing_mode: true,
    passphrase: 'your_passphrase', // REQUIRED
    frequency: SubscriptionFrequency::Monthly,
    subscription_cycles: 12, // 0 for indefinite
    billing_date: new DateTime('2025-12-01'), // Optional
    recurring_amount: 99.99, // Optional, defaults to initial amount
    subscription_notify_email: true,
    subscription_notify_webhook: true,
    subscription_notify_buyer: true
);

// Set customer and transaction details (same as simple integration)
$subscription->set_customer_details('John', 'Doe', '[email protected]');
$subscription->set_transaction_details(
    amount: 99.99,
    item_name: 'Monthly Subscription',
    item_description: 'Premium membership'
);

// Redirect to PayFast
$url = $subscription->get_payment_url();
header("Location: $url");

$subscription->set_transaction_details(
    amount: 0.00, // Free trial
    item_name: 'Trial Subscription'
);



use TshimologoMoeng\Payfast\RecurringBilling\PayfastTokenisation;
use TshimologoMoeng\Payfast\Enums\SubscriptionFrequency;

$tokenization = new PayfastTokenisation(
    merchant_id: 'your_merchant_id',
    merchant_key: 'your_merchant_key',
    testing_mode: true,
    passphrase: 'your_passphrase',
    frequency: SubscriptionFrequency::Monthly,
    subscription_cycles: 0
);

// Set up with R0.00 to just save card details
$tokenization->set_transaction_details(
    amount: 0.00,
    item_name: 'Card Setup'
);

// Get payment URL
$url = $tokenization->get_payment_url();
header("Location: $url");

$updateLink = $tokenization->update_card_details_link(
    token: 'customer-token-from-webhook',
    return: 'https://yoursite.com/account'
);

echo "<a href='$updateLink'>Update Card Details</a>";



use TshimologoMoeng\Payfast\SplitPayments\PayfastSplitPayments;
use TshimologoMoeng\Payfast\Exceptions\PayfastValidationException;

try {
    // Split by percentage
    $split = new PayfastSplitPayments(
        third_party_merchant_id: '10000200',
        percentage: 10, // 10% goes to third party
        min: 5.00, // Minimum R5
        max: 200.00 // Maximum R200
    );

    // OR split by fixed amount
    $split = new PayfastSplitPayments(
        third_party_merchant_id: '10000200',
        amount: 50.00 // R50 goes to third party
    );

    // OR combine both (percentage first, then amount)
    $split = new PayfastSplitPayments(
        third_party_merchant_id: '10000200',
        percentage: 10,
        amount: 5.00
    );

    // Get JSON data to send with payment
    $splitData = $split->setup();

} catch (PayfastValidationException $e) {
    echo $e->getMessage();
    print_r($e->getErrors());
}



shimologoMoeng\Payfast\WebhookHandler\PayfastWebhookHandler;

// Initialize webhook handler
$webhook = new PayfastWebhookHandler(
    merchant_id: 'your_merchant_id',
    merchant_key: 'your_merchant_key',
    testing_mode: true, // Optional - True by default
    passphrase: 'your_passphrase' // Optional
);

// Handle the webhook with expected amount
if ($_SERVER['REQUEST_METHOD'] === "POST") {

    if ($webhook->handle_webhook(expected_amount: 100.00)) {
        if ($webhook->is_payment_complete()) {
            // Logic if the payment went through
        } else {
            // Logic if payment failed / cancelled
        }
    } else {
            // Logic for invalid webhook (Validation failed)
    }
} else {
    // if request is not a post request
}




use TshimologoMoeng\Payfast\WebhookHandler\PayfastSubscriptionWebhookHandler;

$webhook = new PayfastSubscriptionWebhookHandler(
    merchant_id: 'your_merchant_id',
    merchant_key: 'your_merchant_key',
    testing_mode: true,
    passphrase: 'your_passphrase'
);

if ($webhook->handle_webhook(expected_amount: 99.99)) {
    $data = $webhook->get_data();

    $token = $data['token']; // Use for API calls
    $type = $data['type']; // subscription.free-trial, subscription.payment, etc.
    $nextRun = $data['next_run']; // Next billing date

    // Process subscription payment
    // ...
}

use TshimologoMoeng\Payfast\Enums\PaymentMethod;

$payfast->set_transaction_details(
    amount: 100.00,
    item_name: 'Product',
    payment_method: PaymentMethod::Credit_Card
);

// Sandbox (testing)
$payfast = new PayfastSimpleIntegration(
    merchant_id: '10000100',
    merchant_key: '46f0cd694581a',
    testing_mode: true
);

// Production
$payfast = new PayfastSimpleIntegration(
    merchant_id: 'your_live_merchant_id',
    merchant_key: 'your_live_merchant_key',
    testing_mode: false
);

$payfast = new PayfastSimpleIntegration(
    merchant_id: 'your_merchant_id',
    merchant_key: 'your_merchant_key',
    testing_mode: true,
    passphrase: 'your_secure_passphrase'
);

use TshimologoMoeng\Payfast\Exceptions\PayfastValidationException;

try {
    $paymentUrl = $payfast->get_payment_url();
    header("Location: $paymentUrl");
} catch (PayfastValidationException $e) {
    echo $e->getMessage();
    print_r($e->getErrors());
} catch (\Exception $e) {
    error_log("PayFast error: " . $e->getMessage());
    echo "Payment processing error";
}

__construct(
    string $merchant_id,
    string $merchant_key,
    bool $testing_mode = true,
    ?string $passphrase = null,
    ?string $return_url = null,
    ?string $cancel_url = null,
    ?string $notify_url = null,
    ?int $fica_idnumber = null
)

set_customer_details(
    ?string $name_first = null,
    ?string $name_last = null,
    ?string $email_address = null,
    ?string $cell_number = null
): void

set_transaction_details(
    float $amount,
    string $item_name,
    ?string $item_description = null,
    ?string $m_payment_id = null,
    ?bool $email_confirmation = true,
    ?string $confirmation_address = null,
    ?PaymentMethod $payment_method = null
): void

get_payment_url(): string
bash
composer