Integrate your Razorpay Custom web application to accept payments in PhonePe Switch platform.
PhonePe Switch platform allows customers to switch seamlessly between PhonePe and their preferred apps within the PhonePe app itself. With a single tap, customers can log into these apps without downloading them. For example, customers can book cabs or hotel rooms right on the PhonePe app and utilize offers provided by PhonePe.
PhonePe enables various businesses to integrate their web apps or mobile sites with the Switch platform and instantly reach out to the PhonePe user base. By integrating Razorpay APIs with PhonePe Switch payment flow, you can accept in-app payments made by your customers without having to worry about handling settlements or reconciliation separately.
Feature Request
This is an on-demand feature. Please raise a request with our Support team to get this feature activated on your Razorpay account.
integer The transaction amount, expressed in the currency subunit, such as paise (in case of INR). For example, for an actual amount of ₹299.35, the value of this field should be 29935.
currencymandatory
string The currency in which the transaction should be made. You can create Orders in INR only.
receiptoptional
string Your receipt ID for this order can be passed here. Maximum length is 40 characters.
phonepe_switch_contextoptional
json string This is the transactionContext created by PhonePe. It contains the shopping cart details for the customer transacting on the PhonePe Switch platform. It is the transactionContext which is expected by PhonePe. Refer to PhonePe transactionContext documentation.
notesoptional
object Key-value pair that can be used to store additional information about the entity. Maximum 15 key-value pairs, 256 characters (maximum) each. For example, "note_key": "Beam me up Scotty”.
Including the Javascript, not the Library:
Include the script from https://checkout.razorpay.com/v1/razorpay.js instead of serving a copy from your own server. This allows new updates and bug fixes to the library to get automatically served to your application.
We always maintain backward compatibility with our code.
If you need multiple razorpay instances on same page, you can globally set some of the options:
CopyRazorpay.configure({
key: '<YOUR_KEY_ID>',
// logo, displayed in the payment processing popupimage: 'https://i.imgur.com/n5tjHFD.png',
})
newRazorpay({}); // will inherit key and image from above.
Once the order is created and the customer's payment details are obtained, the information should be sent to Razorpay to complete the payment. The data that needs to be submitted depends upon the payment method selected by the customer.
You can do this by invoking createPayment method:
Copyvar data = {
amount: 1000, // in currency subunits. Here 1000 = 1000 paise, which equals to ₹10currency: "INR",
email: 'gaurav.kumar@example.com',
contact: '9123456780',
notes: {
address: 'Ground Floor, SJR Cyber, Laskar Hosur Road, Bengaluru',
},
order_id: "order_EdUtuxhupLSOUH", // Enter the order ID obtained from Step 1method: 'wallet',
wallet: 'phonepeswitch'
};
var btn = document.querySelector('#btn');
btn.addEventListener('click', function(){
razorpay.createPayment(data);
razorpay.on('payment.success', function(resp){
alert(resp.razorpay_payment_id),
alert(resp.razorpay_order_id),
alert(resp.razorpay_signature)
}); // will pass payment ID, order ID, and Razorpay signature to success handler.
razorpay.on('payment.error', function(resp){
alert(resp.error.description)}); // will pass error object to error handler
});
Copyvar data = {
callback_url: 'https://www.examplecallbackurl.com/',
amount: 1000, // in currency subunits. Here 1000 = 1000 paise, which equals to ₹10currency: "INR",
email: 'gaurav.kumar@example.com',
contact: '9123456780',
notes: {
address: 'Ground Floor, SJR Cyber, Laskar Hosur Road, Bengaluru',
},
order_id: "order_EdUtuxhupLSOUH", // Enter the order ID obtained from Step 1method: 'wallet',
wallet: 'phonepeswitch'
};
var btn = document.querySelector('#btn');
btn.addEventListener('click', function(){
razorpay.createPayment(data);
});
Note:
The createPayment method should be called within an event listener triggered by user action to prevent the popup from being blocked. For example:
js $('button').click( function (){ razorpay.createPayment(...) })
Handler Function vs Callback URL:
Handler Function:
When you use the handler function, the response object of the successful payment (razorpay_payment_id, razorpay_order_id and razorpay_signature) is submitted to the Checkout Form. You need to collect these and send them to your server.
Callback URL:
When you use a Callback URL, the response object of the successful payment (razorpay_payment_id, razorpay_order_id and razorpay_signature) is submitted to the Callback URL.
This is a mandatory step to confirm the authenticity of the details returned to the Checkout form for successful payments.
To verify the razorpay_signature returned to you by the Checkout form:
Create a signature in your server using the following attributes:
order_id: Retrieve the order_id from your server. Do not use the razorpay_order_id returned by Checkout.
razorpay_payment_id: Returned by Checkout.
key_secret: Available in your server. The key_secret that was generated from the Razorpay Dashboard.
Use the SHA256 algorithm, the razorpay_payment_id and the order_id to construct a HMAC hex digest as shown below:
Copygenerated_signature = hmac_sha256(order_id + "|" + razorpay_payment_id, secret);
if (generated_signature == razorpay_signature) {
payment is successful
}
If the signature you generate on your server matches the razorpay_signature returned to you by the Checkout form, the payment received is from an authentic source.
Given below are the sample codes for payment signature verification.
Copy/**
* This class defines common routines for generating
* authentication signatures for Razorpay Webhook requests.
*/publicclassSignature
{
privatestaticfinalStringHMAC_SHA256_ALGORITHM="HmacSHA256";
/**
* Computes RFC 2104-compliant HMAC signature.
* * @param data
* The data to be signed.
* @param key
* The signing key.
* @return
* The Base64-encoded RFC 2104-compliant HMAC signature.
* @throws
* java.security.SignatureException when signature generation fails
*/publicstatic String calculateRFC2104HMAC(String data, String secret)throws java.security.SignatureException
{
String result;
try {
// get an hmac_sha256 key from the raw secret bytesSecretKeySpecsigningKey=newSecretKeySpec(secret.getBytes(), HMAC_SHA256_ALGORITHM);
// get an hmac_sha256 Mac instance and initialize with the signing keyMacmac= Mac.getInstance(HMAC_SHA256_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytesbyte[] rawHmac = mac.doFinal(data.getBytes());
// base64-encode the hmac
result = DatatypeConverter.printHexBinary(rawHmac).toLowerCase();
} catch (Exception e) {
thrownewSignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
}
Copyimport (
"crypto/hmac""crypto/sha256""crypto/subtle""encoding/hex""fmt"
)
funcmain() {
signature := "477d1cdb3f8122a7b0963704b9bcbf294f65a03841a5f1d7a4f3ed8cd1810f9b"
secret := "qp3zKxwLZxbMORJgEVWi3Gou"
data := "order_J2AeF1ZpvfqRGH|pay_J2AfAxNHgqqBiI"//fmt.Printf("Secret: %s Data: %s\n", secret, data)// Create a new HMAC by defining the hash type and the key (as byte array)
h := hmac.New(sha256.New, []byte(secret))
// Write Data to it
_, err := h.Write([]byte(data))
if err != nil {
panic(err)
}
// Get result and encode as hexadecimal string
sha := hex.EncodeToString(h.Sum(nil))
fmt.Printf("Result: %s\n", sha)
if subtle.ConstantTimeCompare([]byte(sha), []byte(signature)) == 1 {
fmt.Println("Works")
}
}
After you have successfully completed the integration, you can set up webhooks, make test payments, replace test key with live key and integrate with other APIs.
After payment is authorized, you need to capture it to settle the amount to your bank account as per the settlement schedule. Payments that are not captured are auto-refunded after a fixed time.
Auto-capture payments (recommended) Authorized payments can be automatically captured. You can auto-capture all payments using global settings on the Razorpay Dashboard.
Watch Out!
Payment capture settings work only if you have integrated with Orders API in your server side. Know more about the Orders API.
Manually capture payments Each authorized payment can also be captured individually. You can manually capture payments:
After the integration is complete, a Pay button will appear on your webpage/app.
Click the button and make a test transaction to ensure the integration is working as expected. You can start accepting actual payments from your customers once the test is successful.
You can make test payments using one of the payment methods configured at the Checkout.
No money is deducted from the customer's account as this is a simulated transaction.
Ensure you have entered the API Keys generated in the Test Mode in the Checkout code.
You can select any of the listed banks. After choosing a bank, Razorpay will redirect to a mock page where you can make the payment success or a failure. Since this is Test Mode, we will not redirect you to the bank login portals.
You can select any of the listed wallets. After choosing a wallet, Razorpay will redirect to a mock page where you can make the payment success or a failure. Since this is Test Mode, we will not redirect you to the wallet login portals.
You can use one of the test cards to make transactions in the Test Mode. Use any valid expiration date in the future and any random CVV to create a successful payment.