PHP code example of sitehandy / omnipay-toyyibpay

1. Go to this page and download the library: Download sitehandy/omnipay-toyyibpay 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/ */

    

sitehandy / omnipay-toyyibpay example snippets


use Omnipay\Omnipay;

// Initialize the gateway
$gateway = Omnipay::create('ToyyibPay');
$gateway->setTestMode(true); // Use false for production

// Create a simple payment
$response = $gateway->purchase([
    'userSecretKey' => 'your-secret-key',
    'categoryCode' => 'your-category-code',
    'billName' => 'Product Purchase',
    'billDescription' => 'Payment for product XYZ',
    'billAmount' => 50.00, // RM 50.00
    'billReturnUrl' => 'https://yoursite.com/return',
    'billCallbackUrl' => 'https://yoursite.com/callback',
    'billExternalReferenceNo' => 'ORDER-' . time(),
    'billTo' => 'John Doe',
    'billEmail' => '[email protected]',
    'billPhone' => '0123456789'
])->send();

if ($response->isRedirect()) {
    $response->redirect();
} else {
    echo 'Error: ' . $response->getMessage();
}

use Omnipay\Omnipay;

$gateway = Omnipay::create('ToyyibPay');
$gateway->setTestMode(true);

$response = $gateway->purchase([
    // Required parameters
    'userSecretKey' => 'your-secret-key',
    'categoryCode' => 'your-category-code',
    'billName' => 'Premium Product Package',
    'billDescription' => 'Complete package with premium features',
    'billAmount' => 299.99,
    'billReturnUrl' => 'https://yoursite.com/payment/return',
    'billCallbackUrl' => 'https://yoursite.com/payment/callback',
    'billExternalReferenceNo' => 'ORD-' . date('YmdHis') . '-' . rand(1000, 9999),
    'billTo' => 'Jane Smith',
    'billEmail' => '[email protected]',
    'billPhone' => '+60123456789',
    
    // Optional parameters
    'billPriceSetting' => 0, // 0=fixed, 1=open amount
    'billPayorInfo' => 1, // 0=optional, 1=ce();
    $_SESSION['order_id'] = $options['billExternalReferenceNo'];
    
    $response->redirect();
} else {
    throw new Exception('Payment creation failed: ' . $response->getMessage());
}

// Example for split payment between multiple merchants
$splitPaymentArgs = [
    [
        'userSecretKey' => 'merchant1-secret-key',
        'amount' => 150.00
    ],
    [
        'userSecretKey' => 'merchant2-secret-key', 
        'amount' => 149.99
    ]
];

$response = $gateway->purchase([
    'userSecretKey' => 'main-merchant-secret-key',
    'categoryCode' => 'your-category-code',
    'billName' => 'Marketplace Order',
    'billDescription' => 'Order from multiple vendors',
    'billAmount' => 299.99,
    'billSplitPayment' => 1,
    'billSplitPaymentArgs' => json_encode($splitPaymentArgs),
    // ... other 

// FPX (Online Banking) only
$response = $gateway->purchase([
    'billPaymentChannel' => 1, // FPX only
    // ... other parameters
]);

// Credit/Debit Card only
$response = $gateway->purchase([
    'billPaymentChannel' => 2, // Card only
    // ... other parameters
]);

// All payment methods (default)
$response = $gateway->purchase([
    'billPaymentChannel' => 0, // All methods
    // ... other parameters
]);

$gateway = Omnipay::create('ToyyibPay');

// Use sandbox mode for testing
$gateway->setTestMode(1); 

// You need to pass the following parameters to generate bill code
$options = [
    'userSecretKey' => 'YOURSECRETKEY',
    'categoryCode' => 'CATEGORYCODE',
    'billName' => 'Product Name',
    'billDescription' => 'Product Description',
    'billPriceSetting'=> 0,
    'billPayorInfo'=> 1,
    'billAmount'=> 1,
    'billReturnUrl'=>'https://yourwebsite.com/returnurl',
    'billCallbackUrl'=>'https://yourwebsite.com/callbackurl',
    'billExternalReferenceNo' => 'ORDER123',
    'billTo'=>'Customer Name',
    'billEmail'=>'[email protected]',
    'billPhone'=>'0123456789',
    'billSplitPayment'=> 0,
    'billSplitPaymentArgs'=>'',
    'billPaymentChannel'=> 0,
    'billDisplayMerchant'=> 1,
    'billContentEmail' => 'Sample email content',
    'billChargeToCustomer' => 2
];

// Send a purchase request to create a bill
$response = $gateway->purchase($options)->send();

// Available response method
// $response->isSuccessful(); // is the response successful?
// $response->isRedirect(); // is the response a redirect?
// $response->getTransactionReference(); // a reference generated by the payment gateway
// $response->getTransactionId(); // the reference set by the originating website if available.
// $response->getMessage(); // a message generated by the payment gateway

// Now redirect the customer to the toyyibPay bill payment page
if ($response->isRedirect())
{
    // Do whatever you want here for example saving the data to the database etc
    // and then redirect the customer to the offsite payment gateway
    $response->redirect();
}
else
{
    // Display error message
    exit($response->getMessage());
}

$gateway = Omnipay::create('ToyyibPay');

// Parameters Send a complete purchase request to get the bill transactions
$response = $gateway->completePurchase($options)->send();

// Available response method
// $response->isSuccessful(); // is the response successful?
// $response->isRedirect(); // is the response a redirect?
// $response->getTransactionReference(); // a reference generated by the payment gateway
// $response->getTransactionId(); // the reference set by the originating website if available.
// $response->getMessage(); // a message generated by the payment gateway

if ($response->isSuccessful())
{
    // Do whatever you want here for example saving the data to the database etc
    echo $responsive->getTransactionReference();
}
elseif ($response->isRedirect())
{
    // If the payment is not successful, redirect the customer to the payment page for completion
    $response->redirect();
}
else
{
    // Display error message
    exit($response->getMessage());
}

use Omnipay\Omnipay;
use Omnipay\Common\Exception\InvalidRequestException;
use Exception;

try {
    $gateway = Omnipay::create('ToyyibPay');
    $gateway->setTestMode(true);
    
    $response = $gateway->purchase([
        'userSecretKey' => 'your-secret-key',
        'categoryCode' => 'your-category-code',
        'billName' => 'Test Payment',
        'billDescription' => 'Test payment description',
        'billAmount' => 10.00,
        'billReturnUrl' => 'https://yoursite.com/return',
        'billCallbackUrl' => 'https://yoursite.com/callback',
        'billExternalReferenceNo' => 'TEST-' . time(),
        'billTo' => 'Test Customer',
        'billEmail' => '[email protected]',
        'billPhone' => '0123456789'
    ])->send();
    
    if ($response->isRedirect()) {
        // Success - redirect to payment page
        $response->redirect();
    } else {
        // Handle payment creation failure
        $errorMessage = $response->getMessage();
        error_log('toyyibPay payment creation failed: ' . $errorMessage);
        
        // Show user-friendly error message
        throw new Exception('Unable to process payment. Please try again later.');
    }
    
} catch (InvalidRequestException $e) {
    // Handle validation errors (missing 

try {
    $response = $gateway->completePurchase([
        'billCode' => $_GET['billcode'] ?? null
    ])->send();
    
    if ($response->isSuccessful()) {
        // Payment successful
        $transactionId = $response->getTransactionId();
        $transactionRef = $response->getTransactionReference();
        
        // Update your database
        updateOrderStatus($transactionId, 'paid');
        
        // Redirect to success page
        header('Location: /payment/success?ref=' . $transactionRef);
        exit;
        
    } elseif ($response->isRedirect()) {
        // Payment still pending - redirect back to payment page
        $response->redirect();
        
    } else {
        // Payment failed
        $errorMessage = $response->getMessage();
        error_log('Payment verification failed: ' . $errorMessage);
        
        // Redirect to failure page
        header('Location: /payment/failed?error=' . urlencode($errorMessage));
        exit;
    }
    
} catch (Exception $e) {
    error_log('Payment completion error: ' . $e->getMessage());
    header('Location: /payment/error');
    exit;
}

use PHPUnit\Framework\TestCase;
use Omnipay\Omnipay;

class ToyyibPayGatewayTest extends TestCase
{
    private $gateway;
    
    protected function setUp(): void
    {
        $this->gateway = Omnipay::create('ToyyibPay');
        $this->gateway->setTestMode(true);
    }
    
    public function testPurchaseSuccess()
    {
        $options = [
            'userSecretKey' => 'test-secret-key',
            'categoryCode' => 'test-category',
            'billName' => 'Test Product',
            'billDescription' => 'Test Description',
            'billAmount' => 50.00,
            'billReturnUrl' => 'https://example.com/return',
            'billCallbackUrl' => 'https://example.com/callback',
            'billExternalReferenceNo' => 'TEST-123',
            'billTo' => 'John Doe',
            'billEmail' => '[email protected]',
            'billPhone' => '0123456789'
        ];
        
        $response = $this->gateway->purchase($options)->send();
        
        $this->assertTrue($response->isRedirect());
        $this->assertFalse($response->isSuccessful());
        $this->assertNotEmpty($response->getRedirectUrl());
    }
    
    public function testPurchaseWithMissingParameters()
    {
        $this->expectException(InvalidRequestException::class);
        
        $response = $this->gateway->purchase([
            'billName' => 'Test Product'
            // Missing 

// Test with sandbox environment
$gateway = Omnipay::create('ToyyibPay');
$gateway->setTestMode(true); // Always use test mode for testing

// Use test credentials (get these from toyyibPay sandbox)
$testOptions = [
    'userSecretKey' => 'sandbox-secret-key',
    'categoryCode' => 'sandbox-category-code',
    'billName' => 'Test Payment - ' . date('Y-m-d H:i:s'),
    'billDescription' => 'Integration test payment',
    'billAmount' => 1.00, // Use small amount for testing
    'billReturnUrl' => 'https://httpbin.org/get?return=true',
    'billCallbackUrl' => 'https://httpbin.org/post',
    'billExternalReferenceNo' => 'TEST-' . uniqid(),
    'billTo' => 'Test Customer',
    'billEmail' => '[email protected]',
    'billPhone' => '0123456789'
];

$response = $gateway->purchase($testOptions)->send();

if ($response->isRedirect()) {
    echo "Test payment created successfully!\n";
    echo "Payment URL: " . $response->getRedirectUrl() . "\n";
    echo "Bill Code: " . $response->getTransactionReference() . "\n";
} else {
    echo "Test failed: " . $response->getMessage() . "\n";
}

// Use environment variables for sensitive data
$gateway = Omnipay::create('ToyyibPay');
$gateway->setTestMode(getenv('TOYYIBPAY_TEST_MODE') === 'true');

$options = [
    'userSecretKey' => getenv('TOYYIBPAY_SECRET_KEY'), // Never hardcode
    'categoryCode' => getenv('TOYYIBPAY_CATEGORY_CODE'),
    // ... other options
];

// In your callback handler
function handleCallback()
{
    // Verify the callback is from toyyibPay
    $billCode = $_POST['billcode'] ?? null;
    $status = $_POST['status_id'] ?? null;
    
    if (!$billCode || !$status) {
        http_response_code(400);
        exit('Invalid callback data');
    }
    
    // Verify payment status with toyyibPay API
    $gateway = Omnipay::create('ToyyibPay');
    $response = $gateway->completePurchase(['billCode' => $billCode])->send();
    
    if ($response->isSuccessful()) {
        // Update order status in your database
        updateOrderStatus($billCode, 'paid');
        
        // Send confirmation email
        sendPaymentConfirmation($billCode);
    }
    
    // Always respond with 200 OK to acknowledge receipt
    http_response_code(200);
    echo 'OK';
}

function createPayment($orderData)
{
    // Validate and sanitize input data
    $billAmount = filter_var($orderData['amount'], FILTER_VALIDATE_FLOAT);
    if ($billAmount === false || $billAmount <= 0) {
        throw new InvalidArgumentException('Invalid amount');
    }
    
    $billEmail = filter_var($orderData['email'], FILTER_VALIDATE_EMAIL);
    if ($billEmail === false) {
        throw new InvalidArgumentException('Invalid email address');
    }
    
    $billPhone = preg_replace('/[^0-9+]/', '', $orderData['phone']);
    if (strlen($billPhone) < 10) {
        throw new InvalidArgumentException('Invalid phone number');
    }
    
    // Sanitize text fields
    $billName = htmlspecialchars(trim($orderData['product_name']), ENT_QUOTES, 'UTF-8');
    $billTo = htmlspecialchars(trim($orderData['customer_name']), ENT_QUOTES, 'UTF-8');
    
    return [
        'billAmount' => $billAmount,
        'billEmail' => $billEmail,
        'billPhone' => $billPhone,
        'billName' => $billName,
        'billTo' => $billTo
    ];
}

// Debug: Check your credentials
$gateway = Omnipay::create('ToyyibPay');
$gateway->setTestMode(true); // Make sure this matches your secret key environment

// Test with minimal esting credentials',
    'billAmount' => 1.00,
    'billReturnUrl' => 'https://example.com/return',
    'billCallbackUrl' => 'https://example.com/callback',
    'billExternalReferenceNo' => 'DEBUG-' . time(),
    'billTo' => 'Test',
    'billEmail' => '[email protected]',
    'billPhone' => '0123456789'
])->send();

// Debug callback handler
function debugCallback()
{
    // Log all incoming data
    error_log('Callback received: ' . print_r($_POST, true));
    error_log('Headers: ' . print_r(getallheaders(), true));
    
    // Always respond with 200
    http_response_code(200);
    echo 'OK';
}

// Correct amount formatting
$amountInRM = 50.00; // RM 50.00
$response = $gateway->purchase([
    'billAmount' => $amountInRM, // Library handles conversion automatically
    // ... other parameters
]);

// The library automatically converts RM to cents internally
// RM 50.00 becomes 5000 cents

// Test SSL connectivity
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://toyyibpay.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$result = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    echo "SSL Error: " . $error;
} else {
    echo "SSL connection successful";
}

// Enable debug logging
$gateway = Omnipay::create('ToyyibPay');
$gateway->setTestMode(true);

// Log all requests and responses
class DebugHttpClient implements \Http\Client\HttpClient
{
    private $client;
    
    public function __construct($client)
    {
        $this->client = $client;
    }
    
    public function sendRequest($request)
    {
        error_log('Request: ' . $request->getMethod() . ' ' . $request->getUri());
        error_log('Body: ' . $request->getBody());
        
        $response = $this->client->sendRequest($request);
        
        error_log('Response: ' . $response->getStatusCode());
        error_log('Response Body: ' . $response->getBody());
        
        return $response;
    }
}

// Use debug client
$gateway->setHttpClient(new DebugHttpClient($gateway->getHttpClient()));