TrinityTuts

Razorpay payment gateway php integration tutorial

Last updated on August 28th, 2020 at 04:45 pm

In this tutorial, I will explain to you how we can integrate the Razorpay payment gateway into our PHP Application. Before we start first I will explain what is Razory Pay?. Razorpay is the most implemented payment gateway for online payment in India and also very user-friendly and easy to implement. You can implement payment Razorpay in less than 5 minutes using this tutorial.
Razorpay allows online business and e-commerce sites to accept and process payment modes like Debit Card, Credit Card, Net Banking, UPI and PrePaid Digital Wallets on your website.

Before we start the integration Razorpay payment gateway in our application you need to have a Razorpay account you can get your account using this link.

Prerequisites

Step 1. If you already have a Razorpay account you can log in to your account and in top left corner of your browser, you can click on test mode and get your development API key save your key.

Step 2. Now you can get your test API key details from setting -> API Keys as shown in below image

Step 3. Now in this step, we can add Razorpay payment PHP plugin using the composer. If you want to install the composer to follow this link.

composer require razorpay/razorpay:2.*

Step 4. We need to include the above install the plugin in our plugin and create data in PHP which we pass to Razorpay gateway as shown in the below code.

<?php
    require_once('razorpay-php/Razorpay.php');

    use Razorpay\Api\Api;
    use Razorpay\Api\Errors\SignatureVerificationError;

    $keyId = 'rzp_test_ZN5pRVLs4tU7YF';
    $keySecret = 'YOUR API Keys';
    $displayCurrency = 'INR';

    $api = new Api($keyId, $keySecret);

    //
    // We create an razorpay order using orders api
    // Docs: https://docs.razorpay.com/docs/orders
    //
    $orderData = [
        'receipt'         => 3456,
        'amount'          => 2000 * 100, // 2000 rupees in paise
        'currency'        => 'INR',
        'payment_capture' => 1 // auto capture
    ];

    $razorpayOrder = $api->order->create($orderData);

    $razorpayOrderId = $razorpayOrder['id'];

    $_SESSION['razorpay_order_id'] = $razorpayOrderId;

    $displayAmount = $amount = $orderData['amount'];

    if ($displayCurrency !== 'INR'){
        $url = "https://api.fixer.io/latest?symbols=$displayCurrency&base=INR";
        $exchange = json_decode(file_get_contents($url), true);

        $displayAmount = $exchange['rates'][$displayCurrency] * $amount / 100;
    }

    $checkout = 'automatic';

    if (isset($_GET['checkout']) and in_array($_GET['checkout'], ['automatic', 'manual'], true))
    {
        $checkout = $_GET['checkout'];
    }

    $data = [
        "key"               => $keyId,
        "amount"            => $amount,
        "name"              => "Aneh Thakur",
        "description"       => "Happy to help :)",
        "image"             => "https://s29.postimg.org/r6dj1g85z/daft_punk.jpg",
        "prefill"           => [
            "name"              => "Aneh Thakur",
            "email"             => "customer email",
            "contact"           => "customer mobile",
        ],
        "notes"             => [
            "address"           => "Customer Address",
            "merchant_order_id" => "12312321",
        ],
        "theme"             => [
            "color"             => "#F37254"
        ],
        "order_id"          => $razorpayOrderId,
    ];

    if ($displayCurrency !== 'INR')
    {
        $data['display_currency']  = $displayCurrency;
        $data['display_amount']    = $displayAmount;
    }

    $json = json_encode($data);

?>

https://checkout.razorpay.com/v1/checkout.js
<form name='razorpayform' action="verify.php" method="POST">
    <input type="hidden" name="razorpay_payment_id" id="razorpay_payment_id">
    <input type="hidden" name="razorpay_signature"  id="razorpay_signature" >
</form>

<script>
// Checkout details as a json
var options = <?=$json?>;
/**
 * The entire list of Checkout fields is available at
 * https://docs.razorpay.com/docs/checkout-form#checkout-fields
 */
options.handler = function (response){
    document.getElementById('razorpay_payment_id').value = response.razorpay_payment_id;
    document.getElementById('razorpay_signature').value = response.razorpay_signature;
    document.razorpayform.submit();
};
// Boolean whether to show image inside a white frame. (default: true)
options.theme.image_padding = false;
options.modal = {
    ondismiss: function() {
        console.log("This code runs when the popup is closed");
		window.location = 'cancel.php';
    },
    // Boolean indicating whether pressing escape key 
    // should close the checkout form. (default: true)
    escape: true,
    // Boolean indicating whether clicking translucent blank
    // space outside checkout form should close the form. (default: false)
    backdropclose: false
};
var rzp = new Razorpay(options);
rzp.open();
</script>

Step 5. You have to create two more PHP files verify.php and cancel.php if the user makes a payment or cancel payment then you need to redirect the user to that page. You can print $_POST variable on that page.

That’s it hope this post help you to implement the Razorpay payment gateway in your PHP web application/website. Once you tested successfully you need to change test mode API keys with live keys.