PHP code example of ownpay / ownpay-laravel

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

    

ownpay / ownpay-laravel example snippets


use OwnPay\Laravel\Facades\OwnPay;

// Create a payment
$payment = OwnPay::createPayment([
    'amount' => '1250.00',
    'currency' => 'BDT',
    'description' => 'Premium Subscription',
    'redirect_url' => 'https://example.com/success',
    'cancel_url' => 'https://example.com/cancel',
    'callback_url' => 'https://example.com/webhook',
    'customer_name' => 'John Doe',
    'customer_mail' => '[email protected]',
]);

// Redirect customer to checkout
return redirect($payment->checkoutUrl);

// Get payment status
$payment = OwnPay::getPayment($payment->paymentId);
echo $payment->status->label(); // "Pending", "Completed", etc.

// List transactions
$result = OwnPay::listTransactions([
    'page' => 1,
    'per_page' => 25,
    'status' => 'completed',
]);

foreach ($result['data'] as $transaction) {
    echo $transaction->trxId; // "OP-XXXXX"
    echo $transaction->amount;
}

// Create a refund
$refund = OwnPay::createRefund([
    'trx_id' => 'OP-XXXXX',
    'amount' => '500.00',
    'reason' => 'Customer request',
]);

// Create a customer
$customer = OwnPay::createCustomer([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'phone' => '+8801700000000',
]);

// Test webhook endpoint
$result = OwnPay::testWebhook();

use OwnPay\Laravel\Client\OwnPayClient;

class PaymentController extends Controller
{
    public function __construct(
        private readonly OwnPayClient $ownpay,
    ) {}

    public function store(Request $request)
    {
        $payment = $this->ownpay->createPayment([
            'amount' => $request->input('amount'),
            'currency' => $request->input('currency'),
            'callback_url' => route('webhook.ownpay'),
        ]);

        return response()->json([
            'checkout_url' => $payment->checkoutUrl,
            'payment_id' => $payment->paymentId,
        ]);
    }
}

use OwnPay\Laravel\Facades\OwnPay;
use OwnPay\Laravel\Exception\OwnPayExceptionInterface;

class CheckoutController extends Controller
{
    public function initiate(Request $request)
    {
        try {
            $payment = OwnPay::createPayment([
                'amount' => $request->input('amount'),
                'currency' => $request->input('currency'),
                'description' => $request->input('description'),
                'redirect_url' => route('payment.success'),
                'cancel_url' => route('payment.cancel'),
                'callback_url' => route('webhook.ownpay'),
                'customer_name' => $request->input('customer_name'),
                'customer_mail' => $request->input('customer_email'),
                'metadata' => [
                    'order_id' => $request->input('order_id'),
                ],
            ]);

            // Store payment_id in your database
            // Redirect to checkout
            return redirect($payment->checkoutUrl);

        } catch (OwnPayExceptionInterface $e) {
            return back()->withErrors([
                'payment' => $e->getMessage(),
            ]);
        }
    }

    public function success(Request $request)
    {
        $paymentId = $request->query('payment_id');
        $payment = OwnPay::getPayment($paymentId);

        if ($payment->isSuccess()) {
            // Payment completed successfully
            return view('payment.success', ['payment' => $payment]);
        }

        return view('payment.pending', ['payment' => $payment]);
    }
}

use OwnPay\Laravel\Laravel\Middleware\VerifyWebhookSignature;

Route::post('/webhooks/ownpay', [WebhookController::class, 'handle'])
    ->middleware(VerifyWebhookSignature::class);

protected $listen = [
    \OwnPay\Laravel\Laravel\Events\WebhookReceived::class => [
        \App\Listeners\HandleOwnPayWebhook::class,
    ],
];

namespace App\Listeners;

use OwnPay\Laravel\Laravel\Events\WebhookReceived;

class HandleOwnPayWebhook
{
    public function handle(WebhookReceived $event): void
    {
        match ($event->event) {
            'payment.completed' => $this->handlePaymentCompleted($event),
            'payment.failed' => $this->handlePaymentFailed($event),
            'refund.completed' => $this->handleRefundCompleted($event),
            default => null,
        };
    }

    private function handlePaymentCompleted(WebhookReceived $event): void
    {
        $transactionId = $event->getTransactionId();
        $amount = $event->getAmount();
        $currency = $event->getCurrency();

        // Update your database
        // Send confirmation email
        // etc.
    }

    private function handlePaymentFailed(WebhookReceived $event): void
    {
        // Handle failed payment
    }

    private function handleRefundCompleted(WebhookReceived $event): void
    {
        // Handle completed refund
    }
}

use OwnPay\Laravel\Facades\OwnPay;

// List all transactions
$transactions = OwnPay::listTransactions();

// List with filters
$transactions = OwnPay::listTransactions([
    'status' => 'completed',
    'gateway' => 'bkash',
    'from' => '2024-01-01',
    'to' => '2024-12-31',
    'page' => 1,
    'per_page' => 50,
]);

// Get specific transaction
$transaction = OwnPay::getTransaction('OP-XXXXX');

// Check if refundable
if ($transaction->isRefundable()) {
    // Can create refund
}

use OwnPay\Laravel\Facades\OwnPay;

// Create customer
$customer = OwnPay::createCustomer([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'phone' => '+8801700000000',
]);

// List customers
$customers = OwnPay::listCustomers(['page' => 1]);

// Get customer by email or phone
$customer = OwnPay::getCustomer('[email protected]');

use OwnPay\Laravel\Facades\OwnPay;

// List API keys
$keys = OwnPay::listApiKeys();

// Generate new key
$result = OwnPay::generateApiKey([
    'name' => 'Production Key',
    'scopes' => ['read', 'write'],
]);

echo $result['key']; // Show this to the user ONCE
echo $result['prefix'];

// Revoke key
OwnPay::revokeApiKey($keyId);

use OwnPay\Laravel\Exception\OwnPayExceptionInterface;
use OwnPay\Laravel\Exception\AuthenticationException;
use OwnPay\Laravel\Exception\InvalidRequestException;
use OwnPay\Laravel\Exception\NotFoundException;
use OwnPay\Laravel\Exception\RateLimitException;
use OwnPay\Laravel\Exception\ConnectionException;
use OwnPay\Laravel\Exception\PaymentFailedException;

try {
    $payment = OwnPay::createPayment([...]);
} catch (AuthenticationException $e) {
    // Invalid API key or insufficient permissions
    Log::error('OwnPay auth error: ' . $e->getMessage());
} catch (InvalidRequestException $e) {
    // Validation error
    $errors = $e->getErrorDetails();
    // $errors is an array of {code, message, field}
} catch (NotFoundException $e) {
    // Resource not found
} catch (RateLimitException $e) {
    // Rate limit exceeded
    $retryAfter = $e->getRetryAfter();
} catch (ConnectionException $e) {
    // Network error
} catch (OwnPayExceptionInterface $e) {
    // Catch all OwnPay exceptions
}

use OwnPay\Laravel\ValueObjects\Money;

$money = new Money('100.00', 'USD');
$money->amount; // "100.00"
$money->currency; // "USD"
$money->toFloat(); // 100.0
$money->toCents(); // 10000
$money->format(); // "USD 100.00"

// Arithmetic
$a = new Money('100.00', 'USD');
$b = new Money('50.00', 'USD');
$sum = $a->add($b); // Money('150.00', 'USD')
$diff = $a->subtract($b); // Money('50.00', 'USD')

// Comparison
$a->isGreaterThan($b); // true
$a->equals(new Money('100.00', 'USD')); // true

use OwnPay\Laravel\ValueObjects\PaymentStatus;
use OwnPay\Laravel\ValueObjects\TransactionStatus;
use OwnPay\Laravel\ValueObjects\RefundStatus;

// Payment status
$status = PaymentStatus::from('completed');
$status->isSuccess(); // true
$status->isTerminal(); // true
$status->isActive(); // false
$status->label(); // "Completed"

// Transaction status
$status = TransactionStatus::from('completed');
$status->isRefundable(); // true

// Refund status
$status = RefundStatus::from('completed');
$status->isSuccess(); // true

use Illuminate\Support\Facades\Http;

Http::fake([
    'test.ownpay.org/api/v1/payments' => Http::response([
        'success' => true,
        'data' => [
            'payment_id' => 'pay_123',
            'token' => 'tok_123',
            'checkout_url' => 'https://checkout.ownpay.org/pay_123',
            'status' => 'pending',
        ],
    ], 201),
]);

// Your test code here
$payment = OwnPay::createPayment([...]);
$this->assertSame('pay_123', $payment->paymentId);

use OwnPay\Laravel\Webhook\WebhookVerifier;

$verifier = new WebhookVerifier('test-secret');
$payload = '{"event":"payment.completed","transaction_id":"OP-12345"}';
$signature = $verifier->sign($payload);

$result = $verifier->verify($payload, $signature);
$this->assertSame('payment.completed', $result['event']);
bash
php artisan vendor:publish --tag=ownpay-config
bash
php artisan vendor:publish --tag=ownpay-migrations
php artisan migrate
bash
php artisan ownpay:test
php artisan ownpay:test --json