Skip to content

Transactions

Tracking transactions allows you to show users their payment history and verify payments.

Initiating a Transaction

When you start a payment, you can log it as "pending" in your database.

php
use App\Models\PaystackTransaction;

$reference = \Illuminate\Support\Str::uuid();

// 1. Initialize on Paystack
$response = paystack()->transaction()->initialize([
    'email' => $user->email,
    'amount' => 10000,
    'reference' => $reference
]);

// 2. Log to Database
$user->transactions()->create([
    'paystack_id' => $response['data']['access_code'], // Temporary ID until success
    'reference' => $reference,
    'amount' => 10000,
    'status' => 'pending',
    'currency' => 'GHS'
]);

Verifying a Transaction

After the user returns from the payment page, you must verify the transaction to confirm success.

php
// In your Callback Controller
public function callback(Request $request)
{
    $reference = $request->query('reference');

    // 1. Verify with Paystack
    $status = paystack()->transaction()->verify($reference);

    if ($status['data']['status'] === 'success') {
        // 2. Update local transaction
        $transaction = PaystackTransaction::where('reference', $reference)->first();

        $transaction->update([
            'paystack_id' => $status['data']['id'], // The real Transaction ID
            'status' => 'success',
            'metadata' => $status['data']['metadata']
        ]);

        return redirect('/dashboard')->with('success', 'Payment successful!');
    }
}

Listing Transactions

You can easily display a list of transactions to the user using your local relationship.

php
$transactions = $user->transactions()
    ->orderBy('created_at', 'desc')
    ->paginate(10);

foreach ($transactions as $txn) {
    echo $txn->reference . " - " . $txn->amount_in_ghc . " GHS";
}

Use Case: One-Time Purchases

For selling digital products (e.g., E-books), you can use the transaction status to grant access.

php
public function downloadEbook(User $user)
{
    // Check if they have a successful transaction for the ebook amount
    $hasPaid = $user->transactions()
        ->where('amount', 5000) // 50 GHS
        ->where('status', 'success')
        ->exists();

    if ($hasPaid) {
        return Storage::download('ebook.pdf');
    }

    abort(403, 'Please purchase the book first.');
}

Released under the MIT License.