DEV Community

Debajyoti Das
Debajyoti Das

Posted on • Edited on

Razorpay Order creation and payment using Laravel

Working process:

  • On pressing Buy Now button, all data is being submitted to DB then order is being created in Razorpay table and redirecting to Pay with Razorpay page.

  • On clicking the Pay with Razorpay button the Razorpay payment is verified using the try catch and the order table payment status is being changed from unpaid to paid and razorpay_payment_id, razorpay_signature is being updated in Razorpay table by checking the razorpay_order_id and the session order id is being deleted.

  • Lastly, it is heading to the Success view with the data variable which has the order id.

N.B: When this "callback_url": "route('frontend.payment_success')", is hit, razorpay sends razorpay_payment_id, razorpay_signature, razorpay_order_id and it yields 419 error cause the CSRF token mismatches as the route is a POST route, for that this particular route needs to be added in the VerifyCsrfToken middleware so that the csrf token mismatch is exempted.

public static function order_payment($request, $data)
{
$payment_arr=[];
        try{
if($request->type_of_payment == 'online')
{
$api = new Api(config()->get('razorpay_key_id'), config()->get('razorpay_key_secret'));
//Create Order and save in Database
//Delete Shopping cart products

//Razorpay Payment            
                        $orderData = [
                            'receipt'         => 'rcpt_'.$order_id,
                            'amount'          => $data['tot_amount'] * 100, // 39900 rupees in paise
                            'currency'        => config()->get('currency_code'),
                            'partial_payment' => false,
                        ];

                        $razorpayOrder = $api->order->create($orderData);
}
//Create data in Razorpay table
 RazorpayPayment::create([
                            'razorpay_order_id' => $razorpayOrder->id,
                            'amount' => $razorpayOrder->amount,
                            'receipt_id' => $razorpayOrder->receipt, 
                            'status' => $razorpayOrder->status,
                            'created_ts' => $razorpayOrder->created_at,
                        ]);

//Put order id in session
 session()->put(['order_id'=>$razorpayOrder->id, 'order_mode'=>'razorpay']);

if(isset($razorpayOrder->id))
            {
                return view('frontend.razorpay-payment', $data);
            }
}
Enter fullscreen mode Exit fullscreen mode

Razorpay Payment Blade:

@extends('layouts.frontendLayout')

@push('head_script')
@endpush

@section('content')

<button id="rzp-button1" class="btn btn-primary mb-3 mt-3">Pay with Razorpay</button>


@endsection

@push('footer_script')
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
var options = {
    "key": "{{config()->get('razorpay_key_id')}}", // Enter the Key ID generated from the Dashboard
    "amount": "{{$payment_arr['razorpayOrder']->amount}}", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
    "currency": "{{config()->get('currency_code')}}",
    "name": "{{config()->get('setting.siteName')}}",
    "description": "Test Transaction for purchasing {{$payment_arr['order_id']}}",
    "image": "{{asset('customResource/apy-frontend/images/oxgo.jpg')}}",
    "order_id": "{{$payment_arr['razorpayOrder']->id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1
    "callback_url": "{{route('frontend.payment_success')}}",
    "prefill": {
        "name": "{{session()->get('user.name')}}",
        "email": "{{session()->get('user.email')}}",
        "contact": "1234567890"
    },
    "notes": {
        "address": "Some address"
    },
    "theme": {
        "color": "#3399cc"
    }
};
var rzp1 = new Razorpay(options);
document.getElementById('rzp-button1').onclick = function(e){
    rzp1.open();
    e.preventDefault();
}
</script>
@endpush
Enter fullscreen mode Exit fullscreen mode

Heading to Payment verification controller

public function payment_success(Request $request)
{
$data['order_id'] = session()->get('order_id');
if($request->filled('razorpay_payment_id'))
       $api = new Api(config()->get('razorpay_key_id'), config()->get('razorpay_key_secret'));
            try{
                $attributes = array(
                    'razorpay_order_id' =>  $data['order_id'],
                    'razorpay_payment_id' => $request->razorpay_payment_id,
                    'razorpay_signature' => $request->razorpay_signature,
                );

                $api->utility->verifyPaymentSignature($attributes);

                $rzr_record = RazorpayPayment::where('razorpay_order_id',  $data['order_id'])->first();
                Order::where('order_unique_id', substr($rzr_record->receipt_id,5))->update([
                    'payment_status' => 'paid',
                ]);
                $rzr_record->update([
                    'razorpay_payment_id' => $request->razorpay_payment_id,
                    'razorpay_order_id' => session()->get('order_id'),
                    'razorpay_signature' => $request->razorpay_signature,
                ]);
                session()->forget('order_id');
            }
            catch(SignatureVerificationError $e)
            {
                $success = false;
                $error = 'Razorpay Error : '. $e->getMessage();
                $data['error'] =  $error;
                return view('frontend.order-success',$data); //If error
            }
 return view('frontend.order-success', $data); //If success
}
Enter fullscreen mode Exit fullscreen mode

Routes:

Route::any('/checkout', [HomepageController::class, 'checkout'])->middleware('customer','roleif:customer')->name('checkout');//used any for flash message
        Route::post('/checkout-cart', [HomepageController::class, 'checkout_post'])->name('checkout_post');
        Route::post('/payment-success', [HomepageController::class, 'payment_success'])->name('payment_success'); //Hitting when the payment is done and also verified
Enter fullscreen mode Exit fullscreen mode

VerifyCsrfToken:

protected $except = [
        //
        '/payment-success',
    ];
Enter fullscreen mode Exit fullscreen mode

Top comments (0)