Skip to main content

How to Integrate Razorpay in Kotlin Multiplatform Mobile (KMM) for WebApp JS Browser Target

Integrate Razorpay in KMM for WebApp JS Browser Target

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

Popular posts from this blog

Build Once, Run Anywhere: A Simple Weather App using Kotlin Multiplatform (KMM/KMP/CMP)

Simple Weather App using Kotlin Multiplatform (KMM/KMP) Simple Weather App using Kotlin Multiplatform (KMM/KMP) 🚀 In today’s cross-platform app development world, Kotlin Multiplatform (now popularly known as KMP or KMM ) is a game-changer. It allows us to share business logic across Android and iOS without compromising the native feel and performance of the UI. As a passionate mobile developer, I recently built a Simple Weather Application using KMP (Kotlin Multiplatform Project) . This app is a real-world example of how you can target both Android and iOS platforms with a single codebase using: 💻 Jetpack Compose for Android UI 🍎 SwiftUI for iOS UI ⚙️ Shared business logic in Kotlin 🔗 GitHub Project Link 🌟 Why Kotlin Multiplatform (KMP)? Unlike Flutter or React Native, KMP doesn't replace the native UI — instead, it empowers developers to write platform-s...

Understanding Kotlin Yarn Lock in KMM Projects

Kotlin Yarn Lock in KMM Projects Understanding Kotlin Yarn Lock in KMM Projects As a Kotlin Multiplatform Mobile (KMM) developer, working with JavaScript (JS) targets is a crucial aspect when building truly cross-platform applications. In this post, we’ll dive into the importance of the yarn.lock file in KMM projects, how it functions, and where it fits within your project structure. What is yarn.lock ? The yarn.lock file is a critical component in any KMM project that targets JavaScript, whether it's jsBrowser or jsNode . When managing JavaScript dependencies with Yarn, the yarn.lock file locks down the versions of all installed packages, ensuring that every developer and every environment running your project uses the exact same versions. This consistency is vital for avoiding the dreaded "it works on my machine" problem. Why is yarn.lock Important in KMM? When building a KMM project, you might need to int...

How to Load Images in Kotlin Multiplatform (KMM) Using Coil

How to Load Images in Kotlin Multiplatform (KMM) Using Coil How to Load Images in Kotlin Multiplatform (KMM) Using Coil Feature Description Library Used Coil (Image Loading Library) Platforms Supported Android, iOS, Web, Desktop (via KMM) Key Benefits Fast, lightweight, easy integration Implementation Kotlin Multiplatform with Jetpack Compose & SwiftUI Use Cases Displaying remote/local images, caching, placeholders Introduction to KMM and Coil Kotlin Multiplatform (KMM) allows developers to build cross-platform apps for Android, iOS, Web, and Desktop with a single codebase. One challenge in KMM is image loading since different platforms handle images differently. The Coil image loading library , originally built for Android, now supports Kotlin Multiplatform and integrates smoothly with Jetpack Compose, offering a robust solution. Why Use Coil ...