<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Imalka_dhananja on Medium]]></title>
        <description><![CDATA[Stories by Imalka_dhananja on Medium]]></description>
        <link>https://medium.com/@imalka_dhananja?source=rss-328fde76e362------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*viE43VfKeyzQ784SrDD7Ww.jpeg</url>
            <title>Stories by Imalka_dhananja on Medium</title>
            <link>https://medium.com/@imalka_dhananja?source=rss-328fde76e362------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:02:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imalka_dhananja/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AWS Lambda The Future of Serverless Computing]]></title>
            <link>https://medium.com/@imalka_dhananja/aws-lambda-the-future-of-serverless-computing-02cadf3b4d9a?source=rss-328fde76e362------2</link>
            <guid isPermaLink="false">https://medium.com/p/02cadf3b4d9a</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Imalka_dhananja]]></dc:creator>
            <pubDate>Fri, 30 May 2025 15:52:30 GMT</pubDate>
            <atom:updated>2025-05-30T15:52:30.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1A3tAB6DB6pM1s_u.png" /></figure><h4>In today’s fast-paced world of software development, building and deploying applications quickly and efficiently is critical. This is where <strong>serverless computing</strong> shines — and at the forefront of this movement is <strong>AWS Lambda</strong>, Amazon Web Services’ powerful event-driven compute service.</h4><p>In this article, we’ll explore what AWS Lambda is, how it works, its advantages, common use cases, and when <em>not</em> to use it.</p><h3><strong>What is AWS Lambda?</strong></h3><p><strong>AWS Lambda</strong> is a serverless compute service that lets you run your code <strong>without provisioning or managing servers</strong>. You simply upload your code (called a <em>Lambda function</em>), define the trigger (like an API call, file upload, or database update), and AWS takes care of the rest — scaling, monitoring, and running your function as needed.</p><p>It supports multiple programming languages including <strong>Python, Node.js, Java, Go, .NET, and Ruby.</strong></p><h4><strong>How Does It Work?</strong></h4><p>Here’s the basic flow of a Lambda function:</p><ol><li><strong>You write your function code</strong>.</li><li><strong>You define a trigger</strong>, such as:</li></ol><p><em>An HTTP request via API Gateway</em></p><p><em>A file upload to Amazon S3</em></p><p><em>A new item in a DynamoDB table</em></p><p><em>A scheduled time via CloudWatch Events</em></p><p><strong>3.Lambda automatically runs your function</strong> when the trigger event occurs.</p><p><strong>4.You pay only for the time your code is running</strong> (measured in milliseconds).</p><h4><strong>Why Use AWS Lambda?</strong></h4><ol><li>No Server Management</li></ol><p>You don’t need to launch or manage any servers. AWS handles it all.</p><p>2. Auto-Scaling</p><p>Lambda functions automatically scale depending on the number of incoming requests.</p><p>3. Cost-Efficient</p><p>You only pay when your function is invoked — no charge when idle.</p><p>4. Quick Deployment</p><p>Push your function and go live within minutes. Great for prototyping and microservices.</p><p>5. Built-in High Availability</p><p>Lambda functions run in multiple availability zones by default.</p><h4><strong>Popular Use Cases</strong></h4><ul><li><strong>Real-Time File Processing</strong>: Automatically resize an image after upload to S3.</li><li><strong>Data Transformation</strong>: Process incoming data streams from Kinesis or DynamoDB.</li><li><strong>Backend APIs</strong>: Serve dynamic responses using API Gateway + Lambda.</li><li><strong>Automation</strong>: Schedule tasks like database backups or sending reports.</li><li><strong>Chatbots</strong>: Respond to user input in real-time using services like Amazon Lex.</li></ul><h4><strong>When <em>Not</em> to Use Lambda</strong></h4><p>While Lambda is amazing, it’s not always the right fit. You might want to avoid it if:</p><ul><li>You need <strong>long-running processes</strong> (Lambda has a max timeout of 15 minutes).</li><li>Your app requires <strong>high-performance computing</strong> or <strong>complex threading</strong>.</li><li>You have <strong>large deployment packages</strong> (there are size and memory limits).</li><li>Cold start times are a problem (e.g., real-time apps requiring instant response).</li></ul><h4><strong>The Future is Serverless</strong></h4><p>AWS Lambda is revolutionizing the way developers build applications. With minimal setup, powerful scalability, and a pay-as-you-go model, it empowers developers to focus on code — not infrastructure.</p><p>Whether you’re a solo developer building a side project or a team developing large-scale systems, Lambda is a key tool in the modern cloud-native toolbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02cadf3b4d9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Deploying a Task Time Estimation Model with XGBoost and FastAPI]]></title>
            <link>https://medium.com/@imalka_dhananja/building-and-deploying-a-task-time-estimation-model-with-xgboost-and-fastapi-7a9b96e61a96?source=rss-328fde76e362------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a9b96e61a96</guid>
            <dc:creator><![CDATA[Imalka_dhananja]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 16:48:33 GMT</pubDate>
            <atom:updated>2024-08-26T16:48:35.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymbi2WE6fPvOKDADW9pH-Q.png" /></figure><p>In this article, I will walk you through the development of a machine learning model to estimate task completion time, from preprocessing data to deploying the model using FastAPI. I’ll share the challenges I faced, the solutions I implemented, and the final outcome of my second-year project.</p><p>For this project, the dataset was created manually using Jupyter Notebook. The dataset was designed to estimate task completion times, and I included various features like task title, priority, label, reminder, start time, end time, and due dates. I structured the data carefully to ensure it was representative of real-world scenarios, which would allow the model to make accurate predictions.</p><p>By leveraging the flexibility of Jupyter Notebook, I could iterate quickly, adjust the data as needed, and ensure that it was clean and ready for training the machine learning model.</p><p>This manual creation process allowed for greater control and understanding of the data, ensuring it aligned well with the model’s requirements.</p><h4>1. Problem Statement</h4><p>Accurately estimating task completion time is a common challenge in project management. For this project, I set out to build a machine learning model that can predict how long a task will take to complete, based on various attributes like title, priority, start time, end time, and due dates. This prediction model can be integrated into task management applications to improve productivity by providing better time management insights.</p><h4>2. Dataset</h4><p>To train the model, I manually created a dataset using Jupyter Notebook. The dataset consisted of various features that influence task completion time, including:</p><ul><li><strong>Title:</strong> A short description of the task.</li><li><strong>Priority:</strong> The importance of the task.</li><li><strong>Label:</strong> A category or tag assigned to the task.</li><li><strong>Reminder:</strong> Whether or not a reminder is set for the task.</li><li><strong>Start Time and End Time:</strong> The times when the task is scheduled to start and end.</li><li><strong>Due Date:</strong> The deadline for completing the task.</li></ul><p>Here’s a glimpse of how the data was preprocessed:</p><pre># Encoding categorical features<br>label_encoders = {}<br>for column in [&#39;title&#39;, &#39;reminder&#39;, &#39;priority&#39;, &#39;label&#39;]:<br>    label_encoders[column] = LabelEncoder()<br>    data[column] = label_encoders[column].fit_transform(data[column])<br><br># Convert dueDate to datetime and extract features<br>data[&#39;dueDate&#39;] = pd.to_datetime(data[&#39;dueDate&#39;])<br>data[&#39;dueDate_day&#39;] = data[&#39;dueDate&#39;].dt.day<br>data[&#39;dueDate_month&#39;] = data[&#39;dueDate&#39;].dt.month<br>data[&#39;dueDate_year&#39;] = data[&#39;dueDate&#39;].dt.year</pre><h4>3. Model Training</h4><p>For this task, I selected the <strong>XGBoost</strong> algorithm due to its performance and ability to handle structured data well. I split the dataset into training and testing sets, ensuring the model had a good balance of data for learning and validation. Here’s how I initialized and trained the model.</p><pre># Initialize and train the model<br>model = XGBRegressor(n_estimators=100, random_state=42)<br>model.fit(X_train, y_train)</pre><h4>4. Saving the Model and Encoders</h4><p>After training the model, it’s crucial to save it, along with the label encoders, so they can be loaded later for predictions in the FastAPI app. I used pickle to save both the model and the encoders:</p><pre># Save the trained model<br>model_filename = &#39;xgboost_model.pkl&#39;<br>with open(model_filename, &#39;wb&#39;) as file:<br>    pickle.dump(model, file)</pre><p>This ensures that the model and encoders can be reused without retraining them each time the application starts.</p><h4>5. FastAPI Wrapper</h4><p>To deploy the model, I wrapped it with a FastAPI application. FastAPI is a modern, fast (high-performance) web framework for building APIs with Python. It allows you to easily define API endpoints and handle HTTP requests.</p><p>Here’s an example of the /predict endpoint that takes user input, processes it, and returns the estimated task time:</p><pre>@app.post(&#39;/predict&#39;)<br>def predict(user_input: UserInput):<br>    logger.debug(&quot;Predict endpoint called.&quot;)<br>    try:<br>        estimated_time = estimate_task_time(user_input.dict())<br>        return {&#39;estimated_time&#39;: estimated_time}<br>    except Exception as e:<br>        logger.error(f&quot;Prediction error: {e}&quot;)<br>        raise HTTPException(status_code=500, detail=str(e))</pre><h4>6. Handling Edge Cases</h4><p>A key part of the project was ensuring that the model could handle unseen labels gracefully. For example, if a task title or priority level wasn’t present in the training data, I had to ensure the API could handle it without failing. Here’s how I managed unseen labels:</p><pre># Handle unseen labels<br>try:<br>    user_input[column] = encoder.transform([user_input[column]])[0]<br>except ValueError:<br>    user_input[column] = 0  # Default value for unseen labels</pre><h4>7. Testing the API</h4><p>To test the API, I used tools like Postman and curl. Here’s an example of a request to the /predict endpoint using curl:</p><pre>curl -X POST &quot;http://localhost:8081/predict&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{<br>    &quot;description&quot;: &quot;Complete report&quot;,<br>    &quot;dueDate&quot;: &quot;2024-08-30&quot;,<br>    &quot;endTime&quot;: &quot;17:00&quot;,<br>    &quot;label&quot;: &quot;Work&quot;,<br>    &quot;priority&quot;: &quot;High&quot;,<br>    &quot;reminder&quot;: &quot;Yes&quot;,<br>    &quot;startTime&quot;: &quot;14:00&quot;,<br>    &quot;title&quot;: &quot;Finish report&quot;<br>}&#39;</pre><h4>8. Conclusion</h4><p>Building and deploying a task time estimation model with XGBoost and FastAPI was a challenging yet rewarding project. By carefully preprocessing the data, choosing the right model, and deploying it as an API, I was able to create a functional tool that can be integrated into task management systems. In the future, I plan to improve the model by incorporating more features and optimizing its performance further.</p><p>Thank u..</p><p>……………………………………………………………………………………</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a9b96e61a96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Docker Image Building and Pushing with GitHub Actions]]></title>
            <link>https://medium.com/@imalka_dhananja/automate-docker-image-building-and-pushing-with-github-actions-8c9afc06c227?source=rss-328fde76e362------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c9afc06c227</guid>
            <dc:creator><![CDATA[Imalka_dhananja]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 20:03:03 GMT</pubDate>
            <atom:updated>2024-08-30T16:13:55.338Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuous Integration and Continuous Deployment (CI/CD) pipelines have become essential in modern software development. Automating the process of building, testing, and deploying applications can save time and reduce human error. In this article, we’ll explore how to set up a GitHub Action that builds a Docker image from a Node.js application and pushes it to Docker Hub.</p><h3>Prerequisites</h3><p>Before we dive into the setup, ensure you have the following:</p><ol><li><strong>GitHub Repository</strong>: A repository where your application code is hosted.</li><li><strong>Docker Hub Account</strong>: An account on Docker Hub where the Docker image will be pushed.</li><li><strong>Node.js Application</strong>: A simple Node.js application with a Dockerfile (we’ll create this).</li></ol><h4>Step 1: Create a Simple Node.js Application</h4><p>Let’s start by creating a basic Node.js application. If you already have an application, you can skip this step.</p><ol><li>Create a directory for your project and navigate to it:</li></ol><pre>mkdir node-docker-app<br>cd node-docker-app</pre><p>2. Initialize a new Node.js project:</p><pre>npm init -y</pre><p>3.Create a simple index.js file:</p><pre><br>const express = require(&#39;express&#39;);<br>const app = express();<br>const PORT = process.env.PORT || 3000;<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;Hello World!&#39;);<br>});<br><br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on port ${PORT}`);<br>});</pre><p>4. Install the required dependencies:</p><pre>npm install express</pre><h4><strong>Step 2: Write a Dockerfile</strong></h4><p>Next, we’ll create a Dockerfile that defines how our application should be built and run inside a Docker container.</p><ol><li>Create a file named Dockerfile in the root of your project:</li></ol><pre>FROM node:14-alpine3.15<br><br>WORKDIR /app<br><br>COPY . .<br><br>RUN npm install<br><br>EXPOSE 3000<br><br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><h3>Explanation:</h3><ul><li><strong>Base Image</strong>: We’re using Node.js 14 with an Alpine Linux base, which is a lightweight image.</li><li><strong>WORKDIR</strong>: Sets the working directory inside the container to /app.</li><li><strong>COPY</strong>: Copies the current directory’s contents to the /app directory inside the container.</li><li><strong>RUN npm install</strong>: Installs the Node.js dependencies.</li><li><strong>EXPOSE</strong>: Exposes port 3000, where the application will be running.</li><li><strong>CMD</strong>: The command to start the application.</li></ul><h4>Step 3: Set Up GitHub Actions Workflow</h4><p>Now, we’ll create a GitHub Actions workflow that builds the Docker image and pushes it to Docker Hub whenever there’s a push to the main branch.</p><ol><li>In your repository, create the following directory structure: .github/workflows/.</li><li>Inside the workflows directory, create a file named docker-publish.yml:</li></ol><pre>name: Build and Push Docker Image<br><br>on:<br>  push:<br>    branches:<br>      - main  <br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v3<br><br>      - name: Set up Docker Buildx<br>        uses: docker/setup-buildx-action@v2<br><br>      - name: Login to Docker Hub<br>        uses: docker/login-action@v2<br>        with:<br>          username: ${{ secrets.DOCKER_HUB_USERNAME }}<br>          password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}<br><br>      - name: Build and push Docker image<br>        uses: docker/build-push-action@v5<br>        with:<br>          context: .<br>          push: true<br>          tags: ${{ secrets.DOCKER_HUB_USERNAME }}/my-repo:latest</pre><h3>Explanation:</h3><ul><li><strong>Trigger</strong>: The workflow triggers on any push to the main branch.</li><li><strong>Job</strong>: The job runs on an ubuntu-latest virtual machine.</li><li><strong>Checkout Code</strong>: This step uses the actions/checkout action to pull down the latest code from the repository.</li><li><strong>Set Up Docker Buildx</strong>: Docker Buildx is set up to allow for multi-platform builds.</li><li><strong>Login to Docker Hub</strong>: This step logs into Docker Hub using credentials stored in GitHub Secrets (DOCKER_HUB_USERNAME and DOCKER_HUB_ACCESS_TOKEN).</li><li><strong>Build and Push</strong>: The Docker image is built and pushed to Docker Hub. The image is tagged as latest.</li></ul><h4>Step 4: Store Docker Hub Credentials in GitHub Secrets</h4><p>To securely use your Docker Hub credentials in the workflow, store them as GitHub Secrets:</p><ol><li>Navigate to your GitHub repository, and click on <strong>Settings</strong>.</li><li>In the left sidebar, click on <strong>Secrets and variables</strong> -&gt; <strong>Actions</strong>.</li><li>Click the <strong>New repository secret</strong> button.</li><li>Add the following secrets:</li></ol><ul><li><strong>DOCKER_HUB_USERNAME</strong>: Your Docker Hub username.</li><li><strong>DOCKER_HUB_ACCESS_TOKEN</strong>: A Docker Hub access token (preferred) or your Docker Hub password.</li></ul><h4>Step 5: Push to the Main Branch</h4><p>Finally, push your code to the main branch:</p><pre>git add .<br>git commit -m &quot;Set up Docker build and push with GitHub Actions&quot;<br>git push origin main</pre><p>Once the code is pushed, GitHub Actions will automatically trigger the workflow, build the Docker image, and push it to Docker Hub.</p><h3>Conclusion</h3><p>In this article, we walked through setting up a GitHub Action to automate the process of building and pushing a Docker image to Docker Hub. This automation not only saves time but also ensures that your Docker images are always up-to-date with the latest code. By integrating this into your CI/CD pipeline, you can achieve seamless and efficient deployments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c9afc06c227" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement the Payhere payment gateway (Sandbox) for your web application.]]></title>
            <link>https://medium.com/@imalka_dhananja/how-to-implement-the-payhere-payment-gateway-sandbox-for-your-web-application-5ab22fc09a20?source=rss-328fde76e362------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ab22fc09a20</guid>
            <category><![CDATA[payment-gateway]]></category>
            <dc:creator><![CDATA[Imalka_dhananja]]></dc:creator>
            <pubDate>Sat, 04 May 2024 06:41:02 GMT</pubDate>
            <atom:updated>2024-05-04T06:41:02.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSLtoBEot-PegmZd7OhFHg.png" /><figcaption>Image via —<a href="https://payu.in/blog/how-payment-gateway-integration-with-website-works/"> Pay U Blog</a></figcaption></figure><p>In the realm of e-commerce and online transactions, ensuring a seamless and secure payment process is paramount. One solution that empowers developers to integrate such functionalities effortlessly is PayHere. Designed as a robust payment gateway, PayHere facilitates online payments for businesses of all sizes, offering a reliable infrastructure that ensures transactions are conducted smoothly and securely.</p><p>In this article, we’ll delve into the process of integrating PayHere’s payment gateway into your web application, focusing specifically on sandbox mode. Sandbox environments serve as invaluable testing grounds, allowing developers to simulate payment scenarios without real-world financial implications. This practice not only ensures the functionality of your payment integration but also provides a safe space for refining and debugging your implementation before going live.</p><p>Let’s Start…</p><h3>Step 01.</h3><p><a href="https://sandbox.payhere.lk/merchant/sign-up">PayHere Merchant Portal</a> — Use this link to create a sandbox account.</p><h3>Step 02.</h3><p>I hope you have created your sandbox account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVZn2CcF_Z33b4f-sd023g.png" /></figure><p>I am going to use payment gateway for my php web application.</p><p>Following below step you can add your app name or domain to pay here.</p><ul><li>Browse your side menu with three horizontal lines.</li><li>Then click on the Integrations option</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHv3IRtQuF1hBR7dOjh24A.png" /></figure><p>Inhere merchant id is a unique key for a customer.</p><h3>Step 03.</h3><p>By clicking Add Domain/App Button you can add an app name or domain that you are going to integrate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0C_mI01arGpqXVh6GZomBQ.png" /></figure><ul><li>The secret is a key that is used to identify applications uniquely.</li></ul><p>On that now you can find your application in dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxdQDQqRlX4lZWQOlQaHmw.png" /></figure><p>Now open your project and Documentation link.</p><p><a href="https://support.payhere.lk/sandbox-and-testing">Sandbox &amp; Testing — PayHere — Knowledge base</a> — Documentation link.</p><p>In here, I have explained this according to MVC architecture.</p><p>On that now copy and paste below code on the HTML page</p><pre>function paymentGateway(id) {<br>    var xhttp = new XMLHttpRequest();<br>    xhttp.onreadystatechange = () =&gt; {<br>        if (xhttp.readyState == 4 &amp;&amp; xhttp.status == 200) {<br>            var obj = JSON.parse(xhttp.responseText);<br><br>            var payment = {<br>                &quot;sandbox&quot;: true,<br>                &quot;merchant_id&quot;: &quot;******&quot;, // Replace your Merchant ID<br>                &quot;return_url&quot;: &quot;***********&quot;, // Important<br>                &quot;cancel_url&quot;: &quot;&quot;, // Important<br>                &quot;notify_url&quot;: &quot;http://sample.com/notify&quot;,<br>                &quot;order_id&quot;: obj[&quot;order_id&quot;],<br>                &quot;items&quot;: obj[&quot;items&quot;],<br>                &quot;amount&quot;: obj[&quot;amount&quot;],<br>                &quot;plan_id&quot;: obj[&quot;plan_id&quot;],<br>                &quot;currency&quot;: obj[&quot;currency&quot;],<br>                &quot;hash&quot;: obj[&quot;hash&quot;], // *Replace with generated hash retrieved from backend<br>                &quot;first_name&quot;: obj[&quot;first_name&quot;],<br>                &quot;last_name&quot;: obj[&quot;last_name&quot;],<br>                &quot;email&quot;: obj[&quot;email&quot;],<br>                &quot;phone&quot;: obj[&quot;phone&quot;],<br>                &quot;address&quot;: obj[&quot;address&quot;],<br>                &quot;city&quot;: obj[&quot;city&quot;],<br>                &quot;country&quot;: &quot;Sri Lanka&quot;,<br>                &quot;delivery_address&quot;: &quot;&quot;,<br>                &quot;delivery_city&quot;: &quot;&quot;,<br>                &quot;delivery_country&quot;: &quot;Sri Lanka&quot;,<br>                &quot;custom_1&quot;: &quot;&quot;,<br>                &quot;custom_2&quot;: &quot;&quot;,<br>            };<br><br>            // Payment completed. It can be a successful failure.<br>            payhere.onCompleted = function onCompleted(orderId) {<br>                console.log(&quot;Payment completed. OrderID:&quot; + orderId);<br>                var paymentQueryString = Object.keys(payment).map(key =&gt; key + &#39;=&#39; + encodeURIComponent(payment[key])).join(&#39;&amp;&#39;);<br><br>                window.location.href = &quot;http://localhost/*******;<br><br>                // Note: validate the payment and show success or failure page to the customer<br>            };<br><br>            // Payment window closed<br>            payhere.onDismissed = function onDismissed() {<br>                // Note: Prompt user to pay again or show an error page<br>                console.log(&quot;Payment dismissed&quot;);<br>            };<br><br>            // Error occurred<br>            payhere.onError = function onError(error) {<br>                // Note: show an error page<br>                console.log(&quot;Error:&quot; + error);<br>            };<br><br>            payhere.startPayment(payment);<br>        }<br>    }<br>    xhttp.open(&quot;GET&quot;, &quot;Your....URL?id=&quot; + id, true);<br>    xhttp.send();<br>}<br>    <br></pre><h3>Explanation:</h3><ol><li>Function Definition (paymentGateway): This function is responsible for initiating a payment gateway transaction. It takes an id parameter, presumably representing some identifier related to the transaction or user.</li></ol><p>2. XMLHttpRequest: This is an older method for making asynchronous HTTP requests. It’s being used here to fetch data from a server endpoint.</p><p>3. Request Setup (xhttp.open): It sets up an asynchronous request to a server. The URL is provided dynamically using PHP (&lt;?php echo URLROOT ?&gt;), indicating that the server endpoint might be located there.</p><p>4.Request Sending (xhttp.send): It sends the request to the server.</p><p>5.Response Handling (xhttp.onreadystatechange): This function is executed whenever the state of the XMLHttpRequest object changes. When the state becomes 4 (request finished and response is ready) and the status is 200 (OK), it processes the response.</p><p>6. Parsing JSON Response (JSON.parse): It parses the JSON response received from the server into a JavaScript object (obj).</p><p>7. Constructing Payment Object (payment): It constructs a payment object with various properties necessary for initiating the payment transaction. Many of these properties are extracted from the obj received from the server.</p><p>8. Event Handlers (payhere.onCompleted, payhere.onDismissed, payhere.onError): These are callback functions provided by the PayHere API. They handle events related to the payment process, such as completion, dismissal, and errors.</p><p>9. Starting Payment (payhere.startPayment): It initiates the payment process using the PayHere API, passing the constructed payment object.</p><p>10. Redirecting After Payment (window.location.href): Upon completion of the payment, it redirects the user to a specified URL .</p><p>In the controller,</p><pre>public function payment() {<br>    // Retrieve plan data from the model<br>    $data = $this-&gt;Your_Model-&gt;function_name();<br><br>    // Retrieve user details from the session<br>    $mail = $_SESSION[&#39;user_email1&#39;];<br>    $data2 = $this-&gt;Your_Model-&gt;function_name($mail);<br><br>    // Extract necessary information for payment<br>    $amount = $data[0]-&gt;price;<br>    $merchant_id = &quot;****&quot;;<br>    $order_id = uniqid();<br>    $merchant_secret = &quot;******************&quot;;<br>    $currency = &quot;LKR&quot;;<br>    $name = $data[0]-&gt;name;<br>    $f_name = $data2[0]-&gt;Name;<br>    $address = $data2[0]-&gt;Store_Adress;<br>    $email = $data2[0]-&gt;Email;<br>    $plan_id = $data[0]-&gt;plan_id;<br><br>    // Generate hash for secure transaction<br>    $hash = strtoupper(<br>        md5(<br>            $merchant_id . <br>            $order_id . <br>            number_format($amount, 2, &#39;.&#39;, &#39;&#39;) . <br>            $currency .  <br>            strtoupper(md5($merchant_secret)) <br>        ) <br>    );<br><br>    // Construct an array with payment details<br>    $array = [<br>        &quot;items&quot; =&gt; $name,<br>        &quot;full_name&quot; =&gt; $f_name,<br>        &quot;email&quot; =&gt; $email,<br>        &quot;address&quot; =&gt; $address,<br>        &quot;plan_id&quot; =&gt; $plan_id,<br>        &quot;amount&quot; =&gt; $amount,<br>        &quot;merchant_id&quot; =&gt; $merchant_id,<br>        &quot;order_id&quot; =&gt; $order_id,<br>        &quot;merchant_secret&quot; =&gt; $merchant_secret,<br>        &quot;currency&quot; =&gt; $currency,<br>        &quot;hash&quot; =&gt; $hash,<br>    ];<br><br>    // Convert the array to JSON format<br>    $jsonObj = json_encode($array);<br><br>    // Print the JSON object for use in frontend<br>    print_r($jsonObj);<br>}</pre><h3>Explanation:</h3><ol><li>Data Retrieval: The function retrieves necessary data for the payment transaction, such as user information, from the model and session.</li></ol><p>2. Payment Details: It extracts relevant information required for the payment, including the amount, merchant ID, order ID, merchant secret, currency, and user details.</p><p>3. Hash Generation: A secure hash is generated using the merchant ID, order ID, amount, currency, and merchant secret. This hash helps ensure the integrity of the transaction.</p><p>4. Array Construction: The payment details are organized into an associative array for further processing.</p><p>5. JSON Conversion: The array is converted to JSON format using json_encode() for easy consumption by the frontend.</p><p>6. Output: Finally, the JSON object containing the payment details is printed for use in the frontend JavaScript code.</p><p>Now almost finished. Now run your application.</p><p>IT will Popup the payment gateway UI.(This View details are according to my database)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*mpXKPUCaGFpMI-_tE4PGHQ.png" /></figure><p>Use the below link to get sample data to test a payment.</p><p><a href="https://support.payhere.lk/sandbox-and-testing">Sandbox &amp; Testing — PayHere — Knowledge base</a> — Sample Data for testing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*rKw9ww42EGgiDf-AmjUrcA.png" /></figure><p>Thank u….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ab22fc09a20" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>