Skip to main content

Streamlining Transactions: A Guide to Implementing Razorpay Payment Gateway in PHP




Payment Gateway:

The payment gateway is an online service that authorizes and processes payments for online businesses. It provides a payment network between the customer and the merchant on the final amount (pay amount/order's amount). There are two parts to completing an online transaction.

1.  You will need a payment gateway (to accept the payment details and connect to the payment networks).
2.  A merchant account (to receive the funds).

Some of the commonly used payment gateways are as follows:
PayPal,
Paytm,
Razorpay, etc.

Here, We are talking about the simplest way to integrate Razorpay Payment Gateway. You just need to follow the following steps:

1.  Create a Razorpay account and get an API key and secret key from your account settings.
2.  Open the command prompt, Install composer for PHP dependencies and then install Razorpay via the composer.
3.  Integration of Razorpay payment gateway in your project.
4.  Start accepting online payments via card or bank transactions.

Create a Razorpay account and get an API and secret keys:

1.  Log into your Dashboard with the appropriate credentials.
2.  Select the mode (Test or Live) for which you want to generate the API key.
Note:  You have to generate separate API Keys for the test and live modes. No money is deducted from your account in test mode.
3.  Get your Razorpay keys and save them.
Note:  After generating the keys from the Dashboard download and save them securely. If you do not remember your API Keys, you need to re-generate it from the Dashboard and replace it wherever required.

Install Razorpay: 

The easiest way to install Razorpay that Run the below command on your composer

composer require razorpay/razorpay:2.*

Integration of Razorpay payment gateway in your project:

After all calculations on your side, integrate Razorpay by initializing:

use Razorpay\Api\Api;
$api = new Api($api_key, $api_secret);
 

After initialization, you need to create an order request for Razorpay but before this, if you need to keep some important data (like product_id, amount, discount_amount, etc) which will be used later for updating the database, therefore, you will create an array using key=>value pairs - 

$order_notes = [
    'amount' => '500',...
];


Create an order:

$order = $api->order->create(array(
      'receipt' => '123',
      'amount' => 100,
      'payment_capture' => 1,
      'currency' => 'INR'
    )
);

Note:  'amount' in order request is in paise, So if you have 100 rupees amount then you must need to multiply by 100 ('amount' => 100 * 100)

Fetch order by order_id (when you print $order you will found $order_id) from Razorpay response:

$order_data = $api->order->fetch($order_id);

Paste the Checkout script in your project (You will use all parameters from $order):

[action="YOUR_SITE_URL/method_name"]

<form action="https://www.example.com/payment/success/" method="POST"> // Replace this with your website's success callback URL
<script
    src="https://checkout.razorpay.com/v1/checkout.js"
    data-key="YOUR_KEY_ID" // Enter the Key ID generated from the Dashboard
    data-amount="50000" // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
    data-currency="INR"
    data-order_id="order_CgmcjRh9ti2lP7"//This is a sample Order ID. Pass the `id` obtained in the response of the previous step.
    data-buttontext="Pay with Razorpay"
    data-name="Acme Corp"
    data-description="Test transaction"
    data-image="https://example.com/your_logo.jpg"
    data-prefill.name="Gaurav Kumar"
    data-prefill.email="gaurav.kumar@example.com"
    data-prefill.contact="9999999999"
    data-theme.color="#F37254"
></script>
<input type="hidden" custom="Hidden Element" name="hidden">
</form>


Successful Callback/Response: 

{"razorpay_payment_id": "pay_29QQoUBi66xm2f",  "razorpay_order_id": "order_9A33XWu170gUtm",  "razorpay_signature": "9ef4dffbfd84f1318f6739a3ce19f9d85851857ae648f114332d8401e0949a3d"}

In failed payments, the callback will contain the errors returned by Razorpay.

A successful payment for the Order returns razorpay_order_id, razorpay_payment_id, and razorpay_signature, which is then used for payment verification. You can store these fields in your database.

Fetch Payment by payment_id (You have this razorpay_payment_id for fetch all payment details):

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

Verify the Signature:

Signature verification is a mandatory step to ensure that the callback is sent by Razorpay and the payment is received from an authentic source.

Returned signature from Razorpay, you need to generate on your side, and if it is both are equal then the signature will be verified.

$generated_signature = hmac_sha256($razorpay_order_id + "|" + $razorpay_payment_id, secret);  if ($generated_signature == $razorpay_signature) {    payment is successful  }

Start accepting online payment via card or bank transactions:

You can make test payments using any of the payment methods configured on the Checkout. No money is deducted from the customer's account.

For test card payments you can visit here (https://razorpay.com/docs/payment-gateway/web-integration/standard/#test-cards)




😃 Embrace the joy of coding!

Comments

Popular posts from this blog

JavaScript File Import and Export: A Comprehensive Guide

JavaScript, the language that powers the modern web, has evolved significantly over the years, and its capabilities extend beyond simple script tags in HTML. One of the most important features introduced in ECMAScript 6 (ES6) is the ability to modularize code using import and export statements. This article will dive into JavaScript file import and export, exploring how to effectively organize and share code across multiple files. Understanding Modules: Before ES6, JavaScript needed more built-in support for modules, making it challenging to manage large codebases. ES6 introduced the concept of modules, which allow developers to split their code into reusable and manageable chunks. Modules facilitate better code organization, encapsulation, and the reduction of global scope pollution. Exporting from a Module: In JavaScript, you can export variables, functions, classes, or even objects from a module to be used in other files. The export keyword is used to mark items for export. For exam...

Understanding Asynchronous JavaScript: Exploring async/await, Promises, and Callbacks

  Asynchronous programming is a fundamental aspect of JavaScript that allows you to execute code without blocking the main execution thread. It enables tasks like fetching data from APIs, reading files, or handling user interactions to be executed without freezing the entire application. In this article, we'll dive into the concepts of async/await, Promises, and callbacks – powerful tools that make managing asynchronous operations more elegant and efficient. Callbacks: The Traditional Approach Callbacks are the foundation of asynchronous programming in JavaScript. A callback is a function that is passed as an argument to another function. It's executed after the completion of an asynchronous operation. However, using callbacks can lead to callback hell – a situation where nested callbacks become hard to manage and read. Example: function fetchData(callback) {   setTimeout(() => {     const data = 'Hello, world!';     callback(data);   }, 1000); } fe...

Understanding JavaScript Variables: var, let, and const Explained

  In the dynamic world of JavaScript, the way you declare and use variables can greatly impact your code's behavior and performance. With the introduction of ES6 (ECMAScript 2015), JavaScript developers gained more flexibility and control over variable declarations through the use of three keywords: var, let, and const. In this blog, we'll dive into the differences between these keywords and explore when to use each one. Understanding var, let, and const: var :  The Old Way The var keyword was the traditional way to declare variables in JavaScript. However, it has some quirks that can lead to unexpected behaviors. Variables declared with var are function-scoped, meaning they are accessible within the function where they are declared or globally if declared outside of a function. This scope behavior often caused issues in complex codebases. let :  The Block-Scope Hero ES6 introduced the let keyword to address the scoping issues of var. Variables declared with let are block...