Integrating Razorpay with Salesforce
Introduction
In today’s digital landscape, businesses rely on seamless and efficient payment solutions. Razorpay, a popular payment gateway, offers secure and flexible transaction processing, while Salesforce, the world’s leading CRM, helps businesses manage customer interactions. By integrating Razorpay with Salesforce, organizations can automate payments, generate payment links, and track transactions within Salesforce—leading to better financial management and enhanced user experience.
This step-by-step guide will walk you through the complete integration process, including setting up Razorpay API credentials, creating an Apex Controller, and building a Visualforce page for payment processing.
Why Integrate Razorpay with Salesforce?
Integrating Razorpay with Salesforce brings multiple advantages:
- Seamless Payments: Customers can complete transactions without leaving Salesforce.
- Automated Order Creation: Orders and payments are recorded directly in Salesforce.
- Real-time Payment Tracking: Get instant payment confirmation inside Salesforce.
- Scalability: Ideal for businesses handling high volumes of transactions.
Prerequisites
Before getting started, ensure you have:
- A Razorpay Account: Sign up at Razorpay and generate API keys.
- Salesforce Developer Org: If you don’t have one, sign up at Salesforce Developer Edition.
- Basic Knowledge of Apex and Visualforce: Understanding Apex classes and Visualforce pages will help in the integration.
Step 1: Generate Razorpay API Credentials
- Log in to your Razorpay Dashboard.
- Navigate to Settings > API Keys.
- Click Generate Key to obtain your Key ID and Secret Key.
- Store them securely, as they will be used in our Salesforce integration.
Step 2: Create an Apex Controller to Generate a Razorpay Order
In Salesforce, we need an Apex Controller to communicate with Razorpay’s API and create a payment order.
public class RazorpayIntegration {
private static final String RAZORPAY_KEY_ID = ‘YOUR_RAZORPAY_KEY’;
private static final String RAZORPAY_SECRET = ‘YOUR_RAZORPAY_SECRET’;
public String orderId { get; set; }
public String amount { get; set; }
public String currencyType { get; set; }
public String paymentUrl { get; set; } // Store Payment URL
public RazorpayIntegration() {
this.amount = ‘500’; // Default amount in INR
this.currencyType = ‘INR’; //Default currency type
}
public PageReference createOrder() {
try {
String endpoint = ‘https://api.razorpay.com/v1/orders’;
// Prepare Request Body
Map<String, Object> requestBody = new Map<String, Object>();
requestBody.put(‘amount’, Decimal.valueOf(amount) * 100); // Convert to paise
requestBody.put(‘currency’, currencyType);
requestBody.put(‘receipt’, ‘order_receipt_’ + System.currentTimeMillis());
requestBody.put(‘payment_capture’, true);
// Convert Map to JSON
String requestBodyJson = JSON.serialize(requestBody);
// Prepare HTTP Request
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod(‘POST’);
req.setHeader(‘Authorization’, ‘Basic ‘ + EncodingUtil.base64Encode(Blob.valueOf(RAZORPAY_KEY_ID + ‘:’ + RAZORPAY_SECRET)));
req.setHeader(‘Content-Type’, ‘application/json’);
req.setBody(requestBodyJson);
// Send HTTP Request
Http http = new Http();
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) { //statusCode = 200 means authenticated successfully
Map<String, Object> responseMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
orderId = (String) responseMap.get(‘id’);
System.debug(‘Razorpay Order Created: ‘ + orderId);
// we created both the button and payment link (payment link can be used to pay later)
// Generate Payment Link using Razorpay API
String paymentLinkEndpoint = ‘https://api.razorpay.com/v1/payment_links’;
Map<String, Object> paymentLinkRequest = new Map<String, Object>();
paymentLinkRequest.put(‘amount’, Decimal.valueOf(amount) * 100);
paymentLinkRequest.put(‘currency’, currencyType);
paymentLinkRequest.put(‘accept_partial’, false);
paymentLinkRequest.put(‘expire_by’, (System.currentTimeMillis() / 1000) + 3600); // Expiry in 1 hour
paymentLinkRequest.put(‘reference_id’, orderId);
paymentLinkRequest.put(‘description’, ‘Payment for Order ‘ + orderId);
paymentLinkRequest.put(‘customer’, new Map<String, Object>{
‘name’ => ‘Test User’,
’email’ => ‘test@example.com’,
‘contact’ => ‘9876543210’
});
String paymentLinkRequestJson = JSON.serialize(paymentLinkRequest);
HttpRequest paymentLinkReq = new HttpRequest();
paymentLinkReq.setEndpoint(paymentLinkEndpoint);
paymentLinkReq.setMethod(‘POST’);
paymentLinkReq.setHeader(‘Authorization’, ‘Basic ‘ + EncodingUtil.base64Encode(Blob.valueOf(RAZORPAY_KEY_ID + ‘:’ + RAZORPAY_SECRET)));
paymentLinkReq.setHeader(‘Content-Type’, ‘application/json’);
paymentLinkReq.setBody(paymentLinkRequestJson);
HttpResponse paymentLinkRes = http.send(paymentLinkReq);
if (paymentLinkRes.getStatusCode() == 200) {
Map<String, Object> paymentLinkResponseMap = (Map<String, Object>) JSON.deserializeUntyped(paymentLinkRes.getBody());
paymentUrl = (String) paymentLinkResponseMap.get(‘short_url’);
System.debug(‘Payment Link: ‘ + paymentUrl);
}
else {
System.debug(‘Error creating Razorpay payment link: ‘ + paymentLinkRes.getBody());
}
} else {
System.debug(‘Error creating Razorpay order: ‘ + res.getBody());
}
} catch (Exception e) {
System.debug(‘Exception: ‘ + e.getMessage());
}
return null;
}
}
Step 3: Create a Visualforce Page to Display the Payment Link
The next step is to create a Visualforce page that will display the payment link and the Razorpay checkout button aftr creating an money order.
<apex:page controller=”RazorpayIntegration”>
<apex:form id=”razorpayForm”>
<apex:pageBlock title=”Razorpay Payment”>
<apex:pageBlockSection>
<apex:inputText value=”{!amount}” label=”Amount (INR)” required=”true”/>
<apex:commandButton value=”Create Order” action=”{!createOrder}” rerender=”razorpayButton, paymentSection”/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:outputPanel id=”paymentSection”>
<apex:outputPanel rendered=”{!NOT(ISNULL(paymentUrl))}”>
<p><strong>Payment Link: </strong>
<apex:outputLink value=”{!paymentUrl}” target=”_blank”>{!paymentUrl}</apex:outputLink>
</p>
</apex:outputPanel>
</apex:outputPanel>
<apex:outputPanel id=”razorpayButton”>
<apex:outputText value=”{!orderId}” rendered=”{!NOT(ISNULL(orderId))}” id=”orderIdField”/>
<apex:outputPanel rendered=”{!NOT(ISNULL(orderId))}”>
<script src=”https://checkout.razorpay.com/v1/checkout.js”></script>
<script>
function openRazorpayCheckout() {
var options = {
“key”: “Razorpay_key”, // Replace with your Razorpay Key ID
“amount”: {!amount} * 100,
“currency”: “INR”,
“order_id”: “{!orderId}”,
“handler”: function(response) {
alert(‘Payment successful! Payment ID: ‘ + response.razorpay_payment_id);
}
};
var rzp = new Razorpay(options); // initializes the Razorpay Checkout SDK, creating a payment gateway instance for seamless transactions
rzp.open();
}
</script>
<apex:commandButton value=”Pay Now” onclick=”openRazorpayCheckout(); return false;”/>
</apex:outputPanel>
</apex:outputPanel>
</apex:form>
</apex:page>
Step 4: Testing the Integration
Follow these steps to test if the integration is working properly:
- Open the Visualforce page in your Salesforce org.
- Enter an amount (e.g., 500 INR) and click Create Order.
- The payment link should appear—click it to complete the payment.
- Check the Razorpay Dashboard to verify the transaction.
Step 5: Enhancing the Integration
Here are some ways to improve this integration:
- Use Lightning Web Components (LWC): Replace Visualforce with a modern LWC interface.
- Implement Razorpay Webhooks: Get real-time payment updates inside Salesforce.
- Automate Payment Confirmation: Store transaction details in Salesforce records.
Conclusion
Integrating Razorpay with Salesforce provides a seamless way to process payments while keeping records organized within Salesforce. In this guide, we covered:
✔ How to obtain Razorpay API credentials
✔ Creating an Apex Controller to interact with Razorpay
✔ Implementing a Visualforce page for payment processing
✔ Testing and enhancing the integration