How to implement razorpay refund in laravel?

This guide provides a comprehensive, step-by-step approach to integrating the Razorpay payment gateway into a Laravel or PHP application using the Razorpay package. If you haven't obtained the necessary credentials for the Razorpay Payment Gateway, I suggest reading our article on acquiring Razorpay API Keys.


Please note that this article will focus solely on the refund process. Consequently, topics like the payment process will not be covered. If you need guidance on integrating a payment gateway, please refer to our dedicated post on the subject.



We'll be using the Razorpay package for this integration. To install the Razorpay package, please run the following command.

composer require razorpay/razorpay

I assume you have already set everything up, as the refund process is typically the final step in payment integration. Therefore, we will skip the basics and dive straight into the coding.

public function refundPayment($order_id)
{
    try
    {
        $order = Orders::where('order_id', $order_id)->first();
        // $order->total_price = 99.00;
        $total_price = (int)$order->total_price * 100;

        $api = new Api('public_key_here', 'secret_key_here');
        $response = $api->payment->fetch($order->payment_id)->refund(array("amount"=> $total_price, "speed"=>"normal"));

        if($response->status == 'processed')
        {
           	//PAYMENT IS A SUCCESS
           	//HERE YOU CAN ADD DETAILS INTO DATABASE
           	// MAKE SURE TO SAVE '$response->id' if you want to retrive details for future

        	// UDPATE ORDER / TRANSACTION status
            $order->update(['status' => 'Canceled']);
            
            return redirect()->back()->with('success',__('Refunded successfully'));
        }
        else
        {
            return redirect()->back()->with('error',__('Something went wrong'));
        }
    }
    catch (\Exception $e)
    {
        return redirect()->back()->with('error',$e->getMessage());
    }
}