Back

Step by Step Guide to Building a Razorpay API Integration in PHP

Aug 16, 20248 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of online payments? Let's talk Razorpay. It's a robust payment gateway that's perfect for Indian businesses, and today we're going to walk through integrating it into your PHP application. We'll be using the razorpay/razorpay package, which makes our lives a whole lot easier. So, buckle up and let's get started!

Prerequisites

Before we jump in, make sure you've got:

  • A PHP environment (obviously!)
  • Composer installed (trust me, it's a lifesaver)
  • A Razorpay account with API keys (if you don't have one, go grab it now – I'll wait)

Installation

First things first, let's get that Razorpay package installed. Open up your terminal and run:

composer require razorpay/razorpay

Easy peasy, right? Composer does all the heavy lifting for us.

Configuration

Now, let's set up those API keys. Create a new PHP file and add this:

<?php require_once 'vendor/autoload.php'; use Razorpay\Api\Api; $api = new Api('YOUR_KEY_ID', 'YOUR_KEY_SECRET');

Replace 'YOUR_KEY_ID' and 'YOUR_KEY_SECRET' with your actual Razorpay API keys. And please, for the love of all that is holy, don't commit these to version control!

Creating an Order

Time to create our first order. Here's how:

$orderData = [ 'amount' => 50000, // in paise 'currency' => 'INR', 'receipt' => 'rcpt_12345', 'payment_capture' => 1 ]; $order = $api->order->create($orderData);

Remember, the amount is in paise, so ₹500 becomes 50000.

Implementing the Payment Form

Now for the fun part – the payment form! Here's a simple HTML structure:

<form action="verify.php" method="POST"> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="YOUR_KEY_ID" data-amount="50000" data-currency="INR" data-order_id="<?php echo $order->id; ?>" data-buttontext="Pay with Razorpay" data-name="Your Company Name" data-description="Order Description" data-prefill.name="Customer Name" data-prefill.email="[email protected]" data-theme.color="#F37254" ></script> <input type="hidden" custom="Hidden Element" name="hidden"> </form>

Don't forget to replace YOUR_KEY_ID with your actual key ID!

Handling Payment Success

When a payment succeeds, Razorpay will send a POST request to your server. Let's handle that in verify.php:

<?php require('config.php'); $success = true; $error = "Payment Failed"; if (empty($_POST['razorpay_payment_id']) === false) { $api = new Api($keyId, $keySecret); try { $attributes = array( 'razorpay_order_id' => $_POST['razorpay_order_id'], 'razorpay_payment_id' => $_POST['razorpay_payment_id'], 'razorpay_signature' => $_POST['razorpay_signature'] ); $api->utility->verifyPaymentSignature($attributes); } catch(SignatureVerificationError $e) { $success = false; $error = 'Razorpay Error : ' . $e->getMessage(); } } if ($success === true) { $html = "<p>Your payment was successful</p> <p>Payment ID: {$_POST['razorpay_payment_id']}</p>"; } else { $html = "<p>Your payment failed</p> <p>{$error}</p>"; } echo $html;

Handling Payment Failure

As you can see in the code above, we're already handling failures. If the signature verification fails or if there's no payment ID, we display an error message.

Fetching Payment Details

Want to get more details about a payment? Easy:

$payment = $api->payment->fetch($paymentId);

Now you can access all sorts of juicy details about the payment.

Implementing Webhooks

Webhooks are your friend for handling asynchronous events. Set up a webhook URL in your Razorpay dashboard, then create a script to handle incoming webhook events:

<?php $webhookSecret = "YOUR_WEBHOOK_SECRET"; $requestBody = file_get_contents('php://input'); $signature = $_SERVER['HTTP_X_RAZORPAY_SIGNATURE']; try { $api->utility->verifyWebhookSignature($requestBody, $signature, $webhookSecret); } catch(SignatureVerificationError $e) { // Handle invalid signature http_response_code(400); exit(); } $body = json_decode($requestBody, true); // Handle the event switch ($body['event']) { case 'payment.captured': // Payment was successful break; case 'payment.failed': // Payment failed break; // ... handle other events } http_response_code(200);

Testing

Before you go live, make sure to test thoroughly using Razorpay's test mode. Try different scenarios: successful payments, failed payments, and don't forget to test your webhook handling!

Best Practices and Security Considerations

A few final tips to keep you out of trouble:

  1. Never, ever store API keys in your codebase. Use environment variables.
  2. Always verify the payment signature server-side.
  3. Log everything. You'll thank yourself later when debugging.
  4. Use HTTPS everywhere. No exceptions!

Conclusion

And there you have it! You've just built a Razorpay integration in PHP. Pretty cool, right? Remember, this is just the beginning. Razorpay offers a ton of other features like subscriptions, invoicing, and more. So keep exploring, keep coding, and most importantly, keep having fun!

Happy coding, and may your conversion rates be ever in your favor! 🚀💰