Paystack Payment Initialization using PHP Laravel Backend

nobleokechi

Noble Okechi

Posted on September 12, 2022

Paystack Payment Initialization using PHP Laravel Backend

Initializing paystack transaction from your backend is safer way of building a secured payment integration.

For this content, I will be using postman for my testing. If you are new to postman, check my post on how to setup postman with laravel backend.

Create a Route

Create a route on api.php file with any preferred name.

Route::post('initialize_paystack', [PaystackController::class, 'initialize_paystack'])->name('api.initialize_paystack');
Enter fullscreen mode Exit fullscreen mode

Create a Controller

For this solution, I have a controller called PaystackController and a function inside the controller called initialize_paystack.

To initialize payment, see the code below.

private $initialize_url = "https://api.paystack.co/transaction/initialize";

public function initialize_paystack(Request $request)
    {
        // $amount = number_format($request->amount,2);
        $fields = [
            'email' => $request->user()->email,
            'amount' => $request->amount * 100,
        ];
        $fields_string = http_build_query($fields);
        //open connection
        $ch = curl_init();
        //set the url, number of POST vars, POST data

        curl_setopt($ch,CURLOPT_URL, $this->initialize_url);
        curl_setopt($ch,CURLOPT_POST, true);
        curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer ".env('PAYSTACK_SECRET_KEY'),

        "Cache-Control: no-cache",

        ));

        //So that curl_exec returns the contents of the cURL; rather than echoing it

        curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
        //execute post

        $result = curl_exec($ch);
        $response = json_decode($result);

        return json_encode([
                'data' => $response,
                'metadata' => [
                    'payment_for' => 'token'
                ]
           ]);
    }
Enter fullscreen mode Exit fullscreen mode

Send data from postman

To trigger the initialization, I will send the amount from postman which can also be sent from your frontend.

Image description

Your response will return payment link, which you can use to make a payment or return back to the frontend.

"data": {
        "status": true,
        "message": "Authorization URL created",
        "data": {
            "authorization_url": "https://checkout.paystack.com/zbm34791mm5t9wk",
            "access_code": "zbm34791mm5t9wk",
            "reference": "dod8hghbhc"
        }
    },
Enter fullscreen mode Exit fullscreen mode

Image description

The image above is response gotten after clicking the payment link.

💖 💪 🙅 🚩
nobleokechi
Noble Okechi

Posted on September 12, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related