PHP code example of squipix / laravel-paystack

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

    

squipix / laravel-paystack example snippets


'providers' => [
    ...
    Squipix\Paystack\PaystackServiceProvider::class,
    ...
]

'aliases' => [
    ...
    'Paystack' => Squipix\Paystack\Facades\Paystack::class,
    ...
]



return [

    /**
     * Public Key From Paystack Dashboard
     *
     */
    'publicKey' => env('PAYSTACK_PUBLIC_KEY'),

    /**
     * Secret Key From Paystack Dashboard
     *
     */
    'secretKey' => env('PAYSTACK_SECRET_KEY'),

    /**
     * Paystack Payment URL
     *
     */
    'paymentUrl' => env('PAYSTACK_PAYMENT_URL'),

    /**
     * Optional email address of the merchant
     *
     */
    'merchantEmail' => env('MERCHANT_EMAIL'),

    // Maximum retry attempts for HTTP client (default: 3)
    'retry_attempts' => env('PAYSTACK_RETRY_ATTEMPTS', 3),

    // Delay (ms) between retry attempts (default: 150)
    'retry_delay' => env('PAYSTACK_RETRY_DELAY', 150),

    /*
    |--------------------------------------------------------------------------
    | Enable Package Routes - Feature
    |--------------------------------------------------------------------------
    |
    | This option controls whether the Paystack package should automatically
    | load its built-in web routes. You may disable this if you prefer
    | to define your own routes or extend the functionality manually.
    |
    | Default: false
    |
    */
    'enable_routes' => false,

];

PAYSTACK_PUBLIC_KEY=xxxxxxxxxxxxx
PAYSTACK_SECRET_KEY=xxxxxxxxxxxxx
PAYSTACK_PAYMENT_URL=https://api.paystack.co
[email protected]



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Squipix\Paystack\Facades\Paystack;

/**
 * Class PaymentController
 *
 * Handles Paystack payment initialization, redirection, and callback verification.
 *
 * @package App\Http\Controllers
 */
class PaymentController extends Controller
{
    /**
     * Display the payment form to the user.
     *
     * @return \Illuminate\View\View
    */
    public function index()
    {
        return view('payments.index');
    }

    /**
     * Initialize a Paystack transaction and redirect to the authorization URL.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
    */
    public function redirectToGateway(Request $request)
    {
        $request->validate([
            'name' => 'description
                    ]
                ]
            ]
        ];

        try {
            $response = Paystack::transaction()->initialize($payload);
            $transAuthURL = $response['data']['authorization_url']; 
            
            return redirect($transAuthURL);
        } catch (\Exception $e) {
            Log::error('Paystack Error', ['message' => $e->getMessage()]);
            return back()->with('error', 'Failed to initiate payment.');
        }
    }

    /**
     * Handle the callback from Paystack after payment.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
     */
    public function handleGatewayCallback(Request $request)
    {
        $reference = $request->query('reference');

        try {
            $response = Paystack::transaction()->verify($reference);
            $data = $response['data'];

            // Here, you could store the payment record, send a receipt email, etc.
            return view('payments.success', ['payment' => $data]);
        } catch (\Exception $e) {
            Log::error('Verification Error', ['message' => $e->getMessage()]);
            return redirect('/payment')->with('error', 'Payment verification failed.');
        }
    }
}

@extends('layouts.app')

@section('content')
<div class="container mt-5">
    <div class="card my-5">
        <div class="card-header">
            <h3 class="mb-4 text-center">Pay with Paystack</h3>
        </div>

        <div class="card-body">
            @if(session('error'))
                <div class="alert alert-danger">
                    {{ session('error') }}
                </div>
            @endif

            <form method="POST" action="{{ route('checkout.process') }}">
                @csrf

                <div class="form-group mb-3">
                    <label>Name</label>
                    <input type="text" class="form-control" name="name"              <button type="submit" class="btn btn-success w-100">Pay Now</button>
            </form>
        </div>
    </div>
</div>
@endsection

/**
 *  In the case where you need to pass the data from your 
 *  controller instead of a form
 *  Make sure to send:
 *  eference" => '4g4g5485g8545jg8gj',
        "email" => '[email protected]',
        "currency" => "NGN",
        "orderID" => 23456,
    );

$response = Paystack::transaction()->initialize($data);

return redirect($response['data']['authorization_url']);

/**
 * Initialize a new transaction for a customer.
 *
 * @param array $data {
 *     @type string $email         Customer's email address (reference (optional - auto-generated if omitted).
 *     @type string $callback_url  URL to redirect to after payment (optional).
 *     @type array  $metadata      Custom metadata including custom_fields (optional).
 * }
 * @return array Response from Paystack API.
 */
Paystack::transaction()->initialize(array $data);

/**
 * Verify the status of a transaction using its reference.
 *
 * @param string $ref Unique transaction reference to verify.
 * @return array Response from Paystack API containing transaction details.
 */
Paystack::transaction()->verify(string $ref);

/**
 * Fetch details of a single transaction by its ID or reference.
 *
 * @param string $id_or_ref Optional transaction ID or reference.
 * @return array Response with transaction details.
 */
Paystack::transaction()->fetch(string $id_or_ref);

/**
 * List all transactions for the authenticated Paystack account.
 *
 * @return array Paginated list of transactions.
 */
Paystack::transaction()->list();

/**
 * Charge a customer using a saved authorization code.
 *
 * @param array $data {
 *     @type string $authorization_code  The saved Paystack authorization code (
bash
php artisan vendor:publish --provider="Squipix\Paystack\PaystackServiceProvider"