How to Integrate Razorpay in Kotlin Multiplatform Mobile (KMM) for WebApp JS Browser Target
If you're working with Kotlin Multiplatform Mobile (KMM) and want to integrate Razorpay for payments, you might find plenty of documentation for Android and iOS. However, integrating Razorpay into the WebApp JS Browser target isn't as straightforward. In this blog post, I'll guide you through the steps to get Razorpay working in your KMM project for the WebApp JS Browser target.
Why Kotlin Multiplatform Mobile (KMM)?
KMM allows you to share business logic across Android, iOS, Web, and other platforms, making it easier to maintain a single codebase. But, when it comes to platform-specific features like payments, you need to implement certain functionality separately for each platform.
Integrating Razorpay in the JS Browser Target
To integrate Razorpay for the JS Browser target in KMM, you need to follow a different approach compared to Android or iOS. Below is a working implementation that you can easily integrate into your KMM project.
Step-by-Step Code Implementation
Here's the Kotlin code that you can use to start a Razorpay payment in your JS Browser target:
// Import necessary modules
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.browser.document
import org.w3c.dom.HTMLScriptElement
import org.w3c.dom.HTMLInputElement
import kotlin.js.json
// Function to start the payment process in the browser
fun startPaymentInBrowser(
orderId: String,
onResponsePayment: (String, String, String) -> Unit,
onErrorResponse: (Throwable) -> Unit
) {
val scope = MainScope()
// Launching a coroutine to inject the Razorpay payment form
scope.launch {
injectRazorpayForm(orderId, onResponsePayment, onErrorResponse)
}
}
// Function to inject the Razorpay payment form into the DOM
fun injectRazorpayForm(
orderId: String,
onSuccessResponsePayment: (String, String, String) -> Unit,
onErrorResponse: (Throwable) -> Unit
) {
// Create a form element to hold the Razorpay script
val form = document.createElement("form")
form.setAttribute("id", "payment-form")
// Create the Razorpay script element
val script = document.createElement("script") as HTMLScriptElement
script.src = "https://checkout.razorpay.com/v1/checkout.js"
// Create a hidden input element as required by Razorpay
val hiddenInput = document.createElement("input") as HTMLInputElement
hiddenInput.type = "hidden"
hiddenInput.setAttribute("custom", "Hidden Element")
hiddenInput.name = "hidden"
// Append the script and hidden input to the form
form.appendChild(script)
document.body?.appendChild(form)
console.log("Form injected") // Debug log
// Handle script load event
script.onload = {
console.log("Razorpay script loaded") // Debug log
try {
// Define Razorpay options
val options = json(
"key" to "rzp_test_key", // Replace with your actual key
"currency" to "INR",
"name" to "ORG NAME", // Replace with your actual ORG_NAME
"description" to "Payment for Wallet recharge of Winyway",
"image" to IMAGE_URL, // Replace IMAGE_URL with your actual url
"order_id" to orderId,
"handler" to { response: dynamic ->
try {
// Handle successful payment response
onSuccessResponsePayment.invoke(
response.razorpay_payment_id,
response.razorpay_order_id,
response.razorpay_signature
)
handlePaymentSuccess(
response.razorpay_payment_id,
response.razorpay_order_id,
response.razorpay_signature
)
} catch (e: Throwable) {
// Handle errors during the payment process
onErrorResponse.invoke(e)
console.error("Error in payment handler: ${e.message}")
handlePaymentError(e)
}
},
"theme" to json(
"color" to "#1069BC"
)
)
console.log("Opening Razorpay checkout") // Debug log
// Open the Razorpay checkout form
js("new Razorpay(options).open()")
} catch (e: Throwable) {
// Handle setup errors
console.error("Error setting up Razorpay options or opening checkout: ${e.message}")
onErrorResponse.invoke(e)
handlePaymentError(e)
}
}
// Handle script load error
script.addEventListener("error", {
console.error("Error loading Razorpay script") // Debug log
onErrorResponse.invoke(Exception("Error loading Razorpay script"))
handlePaymentError(Exception("Error loading Razorpay script"))
})
}
// Function to handle payment errors
fun handlePaymentError(error: Throwable) {
// Display error message or log the error
console.error("Payment error: ${error.message}")
}
// Function to handle successful payment responses
fun handlePaymentSuccess(paymentId: String, orderId: String, signature: String) {
// Log or process the successful payment information
console.log("Payment ID: $paymentId")
console.log("Order ID: $orderId")
console.log("Signature: $signature")
}
SEO Keywords
- Kotlin Multiplatform Mobile (KMM)
- Razorpay Integration
- JS Browser Target
- WebApp Payment Integration
- Kotlin for Web Payments
- KMM Razorpay Example
Conclusion
With the code provided above, you can seamlessly integrate Razorpay into your WebApp's JS Browser target in a Kotlin Multiplatform Mobile (KMM) project. This approach ensures that your users have a consistent payment experience across platforms. For more KMM tutorials and integrations, stay tuned to KMM Programming Nest!
Call to Action
If you found this guide helpful, don't forget to share it with your network! Feel free to reach out in the comments section below if you have any questions or run into any issues while integrating Razorpay in your KMM project. Happy coding!
Comments
Post a Comment