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

Fixing the Razorpay-Pod Issue in Kotlin Multiplatform Mobile (KMM) for iOS

Fixing Razorpay CocoaPod Integration in KMM for iOS Fixing Razorpay CocoaPod Integration in KMM for iOS Kotlin Multiplatform Mobile (KMM) enables developers to share code between Android and iOS. However, integrating certain CocoaPods, such as ** razorpay-pod **, can be challenging due to naming conventions. This guide provides a step-by-step solution to resolve these issues, ensuring a smooth integration of Razorpay's SDK into your KMM iOS application. Understanding the Issue When integrating ** razorpay-pod ** into a KMM project, developers may encounter errors related to unresolved modules. This often stems from the hyphen in the pod's name, which can cause KMM to misinterpret the module structure, leading to import issues. Solution: Explicitly Defining the moduleName Step 1: Update Your Gradle Configuration In your shared module's build.gradle.kts file, add the following code to explic...

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 ...