Razorpay is a popular payment gateway that allows businesses to accept online payments seamlessly. One of its features includes generating dynamic QR codes for accepting payments. In this tutorial, we’ll walk through the process of generating a dynamic QR code using Razorpay API in PHP.
Also Read: A Step-by-Step Guide: Integrate Razorpay payment gateway to your PHP website
Generating dynamic QR codes with Razorpay API in PHP offers a convenient solution for accepting online payments. By following the steps outlined in this guide, you can seamlessly integrate QR code generation into your PHP application, enhancing the payment experience for your customers.
A Step-by-Step Guide: Generate Dynamic QR Code with Razorpay API in PHP
Step 1: Razorpay Account:
You need to have a Razorpay account. Sign up at Razorpay if you don’t have one.
Step 2: Razorpay API Keys
To authenticate requests to the Razorpay API, you’ll need your API keys.
Log in to your Razorpay Dashboard and navigate to Settings > API Keys. Here, you’ll find your “Key ID” and “Key Secret.” Copy these credentials as you’ll need them in your PHP script to interact with the Razorpay API securely.
Create an auth.php file and Copy and Paste the following code
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
$razorpay_mode='test'; $razorpay_test_key='rzp_test_TlxM6W37t3zETC'; $razorpay_test_secret_key='kWxmCHmtBYxdaLRLEjsT1hQ0'; $razorpay_live_key='YOUR_KEY_ID'; $razorpay_live_secret_key='YOUR_KEY_SECRET'; if($razorpay_mode=='test'){ $razorpay_key=$razorpay_test_key; $authAPIkey="Basic ".base64_encode($razorpay_test_key.":".$razorpay_test_secret_key); }else{ $authAPIkey="Basic ".base64_encode($razorpay_live_key.":".$razorpay_live_secret_key); $razorpay_key=$razorpay_live_key; } |
Replace ‘YOUR_KEY_ID’ and ‘YOUR_KEY_SECRET’ with your actual Razorpay API key and secret.
Step 3: Create your HTML form to get the customer details
Create an index.php page and Copy and Paste the following code into your index.php file.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<!DOCTYPE html> <html> <head> <title>How to Integrate Razorpay payment gateway in PHP | tutorialswebsite.com</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body style="background-repeat: no-repeat;"> <div class="container"> <div class="row"> <div class="col-xs-12 col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title">Charge Rs.10 INR </h4> </div> <div class="panel-body"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" name="billing_name" id="billing_name" placeholder="Enter name" required="" autofocus=""> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" name="billing_email" id="billing_email" placeholder="Enter email" required=""> </div> <div class="form-group"> <label>Mobile Number</label> <input type="number" class="form-control" name="billing_mobile" id="billing_mobile" min-length="10" max-length="10" placeholder="Enter Mobile Number" required="" autofocus=""> </div> <div class="form-group"> <label>Payment Amount</label> <input type="text" class="form-control" name="payAmount" id="payAmount" value="10" placeholder="Enter Amount" required="" autofocus=""> </div> <!-- submit button --> <button id="PayNow" class="btn btn-success btn-lg btn-block" >Submit & Pay</button> </div> </div> </div> </div> </div> </body> </html> |
Now add the below script code in the index.php file, this code will act on the form submit button click.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<script> //Pay Amount jQuery(document).ready(function($){ jQuery('#PayNow').click(function(e){ $(this).text('Please Wait..'); let billing_name = $('#billing_name').val(); let billing_mobile = $('#billing_mobile').val(); let billing_email = $('#billing_email').val(); var payAmount = $('#payAmount').val(); var request_url="submitpayment.php"; var formData = { billing_name:billing_name, billing_mobile:billing_mobile, billing_email:billing_email, payAmount:payAmount, action:'payOrder' } //console.log(formData); $.ajax({ type: 'POST', url:request_url, data:formData, dataType: 'json', encode:true, }).done(function(data){ if(data.res=='success'){ window.location="payNow.php?pid="+data.qr_id; e.preventDefault(); } if(data.res=='error'){ $('#result').text(data.message); $(this).text('Submit & Pay'); } }); }); }); </script> |
In the above JS code, When the user clicks on the pay now button we will get the customer details like name, email, mobile, and price using JS. Also, you can see the Ajax code to process the Razorpay payment. When payment succeeds or fails you will get redirected to the page based on the above script redirection.
Are you want to get implementation help, or modify or extend the functionality of this script?
A Tutorialswebsite Expert can do it for you.
Step 4: Write the Ajax to Create Dynamic QR using Razorpay API
In this step, we’ve created the ‘submitpayment.php’ code file to manage AJAX post requests.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
<?php if(isset($_POST['action']) && $_POST['action']='payOrder'){ include "auth.php"; // Set transaction details $order_id = uniqid(); $billing_name=$_POST['billing_name']; $billing_mobile=$_POST['billing_mobile']; $billing_email=$_POST['billing_email']; $payAmount=$_POST['payAmount']; $note=$billing_name. " account created"; $postdata=array( "name"=>$billing_name, "email"=> $billing_email, "contact"=>$billing_mobile, "notes" =>array( "notes_key_1"=> $note, "notes_key_2"=> "" ) ); /***** create customer on razorpay ****/ $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.razorpay.com/v1/customers', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>json_encode($postdata), CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', 'Authorization: '.$authAPIkey ), )); $response = curl_exec($curl); curl_close($curl); $customerRes= json_decode($response,true); if(isset($customerRes['error'])){ $errMessage=$customerRes['error']['description']; echo json_encode(['res'=>'error','message'=>$errMessage]); exit; }else{ $customerId=$customerRes['id']; /***** create razorpay qr code **********/ $qrNote="QR code payment of ".$payAmount; $pdesc="Razorpay QR code Payment"; $expiretime=''; $qrpostData=array( "type"=> "upi_qr", "name"=> $billing_name, "usage"=> "single_use", "fixed_amount"=> true, "payment_amount"=> $payAmount*100, "description"=> $pdesc, "customer_id"=> $customerId, "notes"=> array( "purpose"=> $qrNote ) ); $curl1 = curl_init(); curl_setopt_array($curl1, array( CURLOPT_URL => 'https://api.razorpay.com/v1/payments/qr_codes', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>json_encode($qrpostData), CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', 'Authorization: '.$authAPIkey ), )); $response1 = curl_exec($curl1); curl_close($curl1); $qrRes= json_decode($response1,true); if(isset($qrRes['image_url'])){ $qrID=$qrRes['id']; $qrImage=$qrRes['image_url']; echo json_encode(['res'=>'success','customer_id'=>$customerId,'qr_id'=>$qrID,'qrImage'=>$qrImage]); exit; }else{ echo json_encode(['res'=>'error','message'=>'Qr code not generated']); exit; } /***** create razorpay qr code end ****/ } }else{ echo json_encode(['res'=>'error']); exit; } ?> |
In the above code,
2 3 4 |
https://api.razorpay.com/v1/customers |
we are using above API to create customer on Razorpay
2 3 4 |
https://api.razorpay.com/v1/payments/qr_codes |
We are using above API to create dynamic QR code. Also you can check QR Code details in Razorpay account.
Step 5: Create payNow.php file
After successfully created QR image link, we will redirect to payNow.php with parameters “qr_id”.
Create payNow.php file and copy and paste following code:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
<html> <head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="icon" href="https://www.tutorialswebsite.com/wp-content/uploads/2022/02/cropped-favicon.png" type="image/x-icon" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <title>Qr Payment | tutorialswebsite.com</title> <style> .content { position: relative; margin: 10px auto; width: 100%; max-width: 640px; z-index: 1; } .clearfix{ border-bottom: 1px dotted #ccc; margin-bottom: 5px; } .demo-title{ background-color: #ff7127; border-color:#ff7127; color:#fff; padding:10px; text-align:center; } .demo-title h4{ font-size: 22px; font-weight: 700; text-shadow: 2px 2px #ff7127; } </style> </head> <body style="background-repeat: no-repeat;"> <div class="col-md-12"> <div class="content"> <div class="col-lg-12"> <div class="col-xs-12 col-md-12" style="text-align:center;"> <?php if(isset($_GET['pid']) ){ $payid=$_GET['pid']; include "auth.php"; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.razorpay.com/v1/payments/qr_codes/'.$payid, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_HTTPHEADER => array( 'Authorization: '.$authAPIkey ), )); $response = curl_exec($curl); curl_close($curl); $getQr=json_decode($response,true); $qrID=$getQr['id']; $qrImage=$getQr['image_url']; $imageData = base64_encode(file_get_contents($qrImage)); $src = 'data: ;base64,' . $imageData; echo "<img src='".$src."' width='300'>"; } ?> </div> </div> </div> </div> <script> function checkStatus(){ var request_url="checkPaymentStatus.php"; var formData = { qr_id:'<?php echo $payid;?>', action:'checkPaymentStatus' } $.ajax({ type: 'POST', url:request_url, data:formData, dataType: 'json', encode:true, }).done(function(data){ console.log(data); if(data.res=='success'){ window.location="payment-success.php?payid="+data.payid; } if(data.res=='error'){ window.location="payment-failed.php?status=failed"; } }); } setInterval(checkStatus, 1000); </script> </body> </html> |
In the above code, we are using below api link to fetch qr code details using qr_id.
2 3 4 |
https://api.razorpay.com/v1/payments/qr_codes/:qr_code |
When we will get QR code image url, we need to Embed image url to <img> element to display qr code as below image.
Also we are using setInterval function to check payment status every second. we are using “checkPaymentStatus.php” url as ajax to fetch payment status details.
Create checkPaymentStatus.php file and copy and paste below code
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?php if(isset($_POST['action']) && $_POST['action']='checkPaymentStatus'){ include "auth.php"; $qr_id=$_POST['qr_id']; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.razorpay.com/v1/payments/qr_codes/'.$qr_id.'/payments',CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_HTTPHEADER => array( 'Authorization: '.$authAPIkey ), )); $response = curl_exec($curl); curl_close($curl); $paymentRes= json_decode($response,true); if(isset($paymentRes['count']) && $paymentRes['count'] !='0'){ $items=$paymentRes['items']; if(is_array($items) && !empty($items)){ $payid=$items[0]['id']; $payStatus=$items[0]['status']; if($payStatus=='captured'){ echo json_encode(['res'=>'success','payid'=>$payid]); exit; }else{ echo json_encode(['res'=>'error','message'=>"Payment not captured"]); exit; } }else{ echo json_encode(['res'=>'error','message'=>"Payment not captured"]); exit; } } }else{ echo json_encode(['res'=>'error']); exit; } ?> |
If payment captured successfully then you will redirect to payment success page.
Are you want to get implementation help, or modify or extend the functionality of this script?
A Tutorialswebsite Expert can do it for you.
Step 6: Create a Payment Success Page
Use the below payment-success.php file code
2 3 4 5 6 7 8 9 10 11 |
<?php if(isset($_GET)){ echo "<pre>"; print_r($_GET); echo "</p>"; } ?> |
That’s it. Now here you can add your own custom code to display success page layout and design.
Wrapping Words
In this tutorial, we learned how to generate a dynamic QR code using Razorpay API in PHP. Dynamic QR codes provide a convenient way to accept payments by allowing customers to scan the code and complete the transaction instantly. With Razorpay, integrating payment solutions into your PHP application becomes straightforward and efficient.
Note: Please replace ‘YOUR_API_KEY’, ‘YOUR_SECRET_KEY’, and other placeholders with your actual credentials and data.
Do you want to get implementation help, or modify or extend the functionality of this script? Submit a paid service request
FAQs
A dynamic QR code is a type of QR code that can change its details, typically used for transactions where the amount or details vary. Using dynamic QR codes with Razorpay API ensures flexibility and security in processing payments.
Yes, you need to have a Razorpay account to access their API and generate dynamic QR codes. Signing up for an account is free and can be done on their website.
Yes, Razorpay’s API is designed for easy integration into PHP applications.
If you don’t have an account, sign up for a Razorpay account at https://dashboard.razorpay.com/
Log in to your Razorpay Dashboard and navigate to Account & Settings > API Keys. Here, you’ll find your “Key ID” and “Key Secret.”
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co