PHP code example of wio / wiopayments

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

    

wio / wiopayments example snippets




use Wio\WioPayments\WioPayments;

$wioPayments = new WioPayments(
    apiKey: env('WIOPAYMENTS_API_KEY'),
    secretKey: env('WIOPAYMENTS_SECRET_KEY')
);



use Wio\WioPayments\WioPayments;
use Wio\WioPayments\Exceptions\PaymentFailedException;

try {
    $wioPayments = new WioPayments(
        apiKey: 'your_api_key',
        secretKey: 'your_secret_key'
    );

    $paymentResponse = $wioPayments->charge(
        currency: 'USD',
        amountInCents: 2999, // $29.99
        metadata: [
            'customer_id' => 'cust_12345',
            'order_id' => 'order_67890',
            'description' => 'Premium subscription'
        ]
    );

    if ($paymentResponse->isSuccessful()) {
        // Payment completed successfully
        $paymentId = $paymentResponse->id;
        $transactionFee = $paymentResponse->fee;
        
        // Store payment information in your database
        // Send confirmation email to customer
        
        echo "Payment processed successfully. ID: {$paymentId}";
    } else {
        // Payment 

$response = $wioPayments->charge(
    currency: 'USD',
    amountInCents: 5000, // $50.00
    metadata: [
        'customer_email' => '[email protected]',
        'product_sku' => 'PROD-001'
    ]
);

$intent = $wioPayments->createPaymentIntent(
    currency: 'EUR',
    amountInCents: 2500, // €25.00
    options: [
        'payment_methods' => ['card', 'sepa_debit'],
        'customer_id' => 'cust_12345',
        'automatic_payment_methods' => true
    ]
);

// Return client_secret to frontend for completion
$clientSecret = $intent->client_secret;

$payment = $wioPayments->getPayment('pay_1234567890');

echo "Payment Amount: " . WioPayments::formatAmount($payment->amount, $payment->currency);
echo "Payment Status: " . $payment->status;
echo "Created: " . $payment->created_at;

// Full refund
$refundResponse = $wioPayments->refund(
    paymentId: 'pay_1234567890',
    metadata: ['reason' => 'customer_request']
);

// Partial refund
$partialRefund = $wioPayments->refund(
    paymentId: 'pay_1234567890',
    amountInCents: 1000, // $10.00 refund
    metadata: ['reason' => 'partial_return']
);

$cancellation = $wioPayments->cancelPayment(
    paymentId: 'pay_1234567890',
    options: [
        'reason' => 'requested_by_customer',
        'metadata' => ['cancelled_by' => 'customer_service']
    ]
);

$customer = $wioPayments->createCustomer([
    'email' => '[email protected]',
    'name' => 'John Doe',
    'phone' => '+1-555-123-4567',
    'address' => [
        'line1' => '123 Main Street',
        'city' => 'New York',
        'state' => 'NY',
        'postal_code' => '10001',
        'country' => 'US'
    ],
    'metadata' => [
        'user_id' => '12345',
        'signup_date' => '2024-01-15'
    ]
]);

$customerId = $customer['id'];

$customerData = $wioPayments->getCustomer('cust_12345');
$customerPayments = $wioPayments->getCustomerPayments('cust_12345', [
    'limit' => 50,
    'status' => 'succeeded'
]);

$updatedCustomer = $wioPayments->updateCustomer('cust_12345', [
    'email' => '[email protected]',
    'metadata' => ['last_updated' => date('Y-m-d H:i:s')]
]);

$checkoutSession = $wioPayments->createCheckoutSession(
    currency: 'USD',
    amountInCents: 4999, // $49.99
    options: [
        'success_url' => 'https://yourstore.com/success?session_id={CHECKOUT_SESSION_ID}',
        'cancel_url' => 'https://yourstore.com/cancelled',
        'customer_email' => '[email protected]',
        'payment_methods' => ['card', 'klarna', 'afterpay'],
        'shipping_address_collection' => true,
        'expires_at' => time() + 3600, // 1 hour expiration
        'metadata' => [
            'order_id' => 'ORD-12345'
        ]
    ]
);

// Redirect customer to checkout
header("Location: " . $checkoutSession['url']);

// Get payment statistics
$statistics = $wioPayments->getPaymentStatistics([
    'start_date' => '2024-01-01',
    'end_date' => '2024-01-31',
    'group_by' => 'day',
    'currency' => 'USD'
]);

// List payments with advanced filtering
$payments = $wioPayments->listPayments([
    'status' => 'succeeded',
    'currency' => 'USD',
    'start_date' => '2024-01-01',
    'end_date' => '2024-01-31',
    'customer_id' => 'cust_12345',
    'min_amount' => 1000, // $10.00 minimum
    'max_amount' => 10000, // $100.00 maximum
    'limit' => 100,
    'page' => 1
]);

// Get payments by date range
$rangePayments = $wioPayments->getPaymentsByDateRange(
    startDate: '2024-01-01',
    endDate: '2024-01-31',
    options: [
        'status' => 'succeeded',
        'currency' => 'USD'
    ]
);



// In your webhook endpoint (e.g., /webhook/wiopayments)
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_WIO_SIGNATURE'] ?? '';
$timestamp = $_SERVER['HTTP_WIO_TIMESTAMP'] ?? '';

try {
    // Verify webhook authenticity
    $isValid = $wioPayments->verifyWebhookSignature(
        payload: $payload,
        signature: $signature,
        timestamp: $timestamp
    );

    if (!$isValid) {
        http_response_code(400);
        exit('Invalid webhook signature');
    }

    // Process verified webhook
    $event = $wioPayments->handleWebhook($payload, $signature, $timestamp);
    
    // Handle different event types
    switch ($event['type']) {
        case 'payment.succeeded':
            // Update order status, send confirmation email
            handleSuccessfulPayment($event['data']);
            break;
            
        case 'payment.failed':
            // Log failure, notify customer
            handleFailedPayment($event['data']);
            break;
            
        case 'refund.created':
            // Process refund, update inventory
            handleRefundCreated($event['data']);
            break;
    }

    http_response_code(200);
    echo 'Webhook processed successfully';

} catch (Exception $e) {
    error_log('Webhook processing failed: ' . $e->getMessage());
    http_response_code(500);
    exit('Webhook processing failed');
}

// Check supported currencies
$supportedCurrencies = WioPayments::getSupportedCurrencies();
// Returns: ['USD', 'EUR', 'GBP', 'CAD', 'AUD', 'JPY', 'TRY', ...]

// Validate currency support
$isSupported = WioPayments::isCurrencySupported('TRY'); // true

// Format amounts with proper currency symbols
echo WioPayments::formatAmount(2999, 'USD'); // $29.99
echo WioPayments::formatAmount(2999, 'EUR'); // €29.99
echo WioPayments::formatAmount(2999, 'JPY'); // ¥2,999 (no decimals)
echo WioPayments::formatAmount(2999, 'TRY'); // ₺29.99

// Convert between dollars and cents
$cents = WioPayments::toCents(29.99);   // 2999
$dollars = WioPayments::fromCents(2999); // 29.99

// Safe decimal handling for financial calculations
$totalCents = WioPayments::toCents(19.99) + WioPayments::toCents(5.00); // 2499
$totalDollars = WioPayments::fromCents($totalCents); // 24.99

// Enable test mode for development
$wioPayments->setTestMode(true);

// Create test payments with specific scenarios
$testPayment = $wioPayments->createTestPayment(
    currency: 'USD',
    amountInCents: 1000,
    scenario: 'success' // 'success', 'failure', 'timeout'
);

// Simulate webhook events for testing
$webhookSimulation = $wioPayments->simulateWebhook(
    eventType: 'payment.succeeded',
    data: [
        'payment_id' => 'test_pay_123',
        'amount' => 1000,
        'currency' => 'USD'
    ]
);

// Check if in test mode
if ($wioPayments->isTestMode()) {
    echo "Running in test mode - no real charges will be made";
}

$validation = $wioPayments->validateApiCredentials();

if ($validation['valid']) {
    $accountInfo = $validation['account_info'];
    echo "API connection successful";
    echo "Account ID: " . $accountInfo['account_id'];
    echo "Business Name: " . $accountInfo['business_name'];
} else {
    echo "API credential validation failed: " . $validation['error'];
}

// Get account information
$accountInfo = $wioPayments->getAccountInfo();
echo "Account Type: " . $accountInfo['account_type'];
echo "Business Name: " . $accountInfo['business_name'];

// Check account balance
$balance = $wioPayments->getBalance();
foreach ($balance['available'] as $currency) {
    echo "Available {$currency['currency']}: " . 
         WioPayments::formatAmount($currency['amount'], $currency['currency']);
}

use Wio\WioPayments\Exceptions\{
    InvalidCredentialsException,
    InvalidCurrencyException,
    PaymentFailedException,
    WioPaymentsException
};

try {
    $payment = $wioPayments->charge('USD', 2999);
    
} catch (InvalidCredentialsException $e) {
    // Authentication or authorization errors
    error_log('API credentials invalid: ' . $e->getMessage());
    
} catch (InvalidCurrencyException $e) {
    // Currency validation or amount errors
    error_log('Currency error: ' . $e->getMessage());
    
} catch (PaymentFailedException $e) {
    // Payment processing failures
    $errorCode = $e->getCode();
    $errorMessage = $e->getMessage();
    
    // Log detailed error information
    error_log("Payment failed (Code: {$errorCode}): {$errorMessage}");
    
} catch (WioPaymentsException $e) {
    // General SDK errors
    error_log('WioPayments SDK error: ' . $e->getMessage());
    
} catch (Exception $e) {
    // Unexpected errors
    error_log('Unexpected error: ' . $e->getMessage());
}

// config/app.php
'providers' => [
    // ...
    Wio\WioPayments\WioPaymentsServiceProvider::class,
],

'aliases' => [
    // ...
    'WioPayments' => Wio\WioPayments\Facades\WioPayments::class,
],



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Wio\WioPayments\WioPayments;
use Wio\WioPayments\Exceptions\PaymentFailedException;

class PaymentController extends Controller
{
    public function __construct(
        private WioPayments $wioPayments
    ) {}

    public function processPayment(Request $request)
    {
        $request->validate([
            'amount' => 'mer_email,
                    'user_id' => auth()->id(),
                    'ip_address' => $request->ip()
                ]
            );

            return response()->json([
                'success' => true,
                'payment_id' => $paymentResponse->id,
                'status' => $paymentResponse->status,
                'amount' => WioPayments::formatAmount(
                    $paymentResponse->amount, 
                    $paymentResponse->currency
                )
            ]);

        } catch (PaymentFailedException $e) {
            return response()->json([
                'success' => false,
                'error' => 'Payment processing failed',
                'message' => $e->getMessage()
            ], 422);
        }
    }
}

use Wio\WioPayments\Facades\WioPayments;

// Process payment using facade
$response = WioPayments::charge('USD', 2999);

// Format currency
$formatted = WioPayments::formatAmount(2999, 'USD');
bash
php artisan vendor:publish --provider="Wio\WioPayments\WioPaymentsServiceProvider"