---
page_source: https://docs.hdfcbank.juspay.in/docs/hypercheckout-mobile-sdk/flutter/how-to-integrate-sdks/handle-payment-responses
page_title: Handle Payment Responses
---


# Handle Payment Responses




### Step 1 Add Juspay Order Status function in your backend


After being redirected to `return_url` from bank page, it is mandatory to do a Server-to-Server Order Status API call to determine the payment status. Please ensure that you verify the order ID and transaction amount.

If you are listening to webhooks from SmartGateway, please refer to the [Webhooks](/hypercheckout-mobile-sdk/web/resources/webhooks) section.

Expose `/handleJuspayResponse` API endpoint on your backend that calls the `Order Status` function of nodejs SDK. This API endpoint will be called from your frontend to fetch the payment status.

For ease of implementation, you can refer to orderStatus function from ‘index.js’ file.



#### Code Snippets: -

#### NodeJS Code Snippet:

```nodejs
const fs = require('fs')
const express = require('express')
// block:start:importing-sdk
const { Juspay, APIError } = require('expresscheckout-nodejs')
// block:end:importing-sdk

/**
 * Setup expresscheckout-node sdk
 */
const SANDBOX_BASE_URL = "https://smartgateway.hdfcuat.bank.in"
const PRODUCTION_BASE_URL = "https://smartgateway.hdfc.bank.in"


/**
 * Read config.json file
 */
const config = require('./config.json')
const path = require('path')
const publicKey = fs.readFileSync(config.PUBLIC_KEY_PATH)
const privateKey = fs.readFileSync(config.PRIVATE_KEY_PATH)
const paymentPageClientId = config.PAYMENT_PAGE_CLIENT_ID // used in orderSession request

/*
Juspay.customLogger = Juspay.silentLogger
*/
const juspay = new Juspay({
    merchantId: config.MERCHANT_ID,
    baseUrl: SANDBOX_BASE_URL,
    jweAuth: {
        keyId: config.KEY_UUID,
        publicKey,
        privateKey
    }
})

/**
 * initialize server
 */
const app = express()
const port = process.env.PORT || 5000

app.use(express.urlencoded({ extended: true }))

/**
 * route:- initiateJuspayPayment
 */

// block:start:session-function
app.post('/initiateJuspayPayment', async (req, res) => {
    const orderId = `order_${Date.now()}`
    const amount = 1 + Math.random() * 100 | 0

    // makes return url
    const returnUrl = `${req.protocol}://${req.hostname}:${port}/handleJuspayResponse`

    try {
        const sessionResponse = await juspay.orderSession.create({
            order_id: orderId,
            amount: amount,
            payment_page_client_id: paymentPageClientId,                    // [required] shared with you, in config.json
            customer_id: 'hdfc-testing-customer-one',                       // [optional] your customer id here
            action: 'paymentPage',                                          // [optional] default is paymentPage
            return_url: returnUrl,                                          // [optional] default is value given from dashboard
            currency: 'INR'                                                 // [optional] default is INR
        })

        // removes http field from response, typically you won't send entire structure as response
        return res.json(makeJuspayResponse(sessionResponse))
    } catch (error) {
        if (error instanceof APIError) {
            // handle errors comming from juspay's api
            return res.json(makeError(error.message))
        }
        return res.json(makeError())
    }
})
 // block:end:session-function

// block:start:order-status-function
app.post('/handleJuspayResponse', async (req, res) => {
    const orderId = req.body.order_id || req.body.orderId

    if (orderId == undefined) {
        return res.json(makeError('order_id not present or cannot be empty'))
    }

    try {
        const statusResponse = await juspay.order.status(orderId)
        const orderStatus = statusResponse.status
        let message = ''
        switch (orderStatus) {
            case "CHARGED":
                message = "order payment done successfully"
                break
            case "PENDING":
            case "PENDING_VBV":
                message = "order payment pending"
                break
            case "AUTHORIZATION_FAILED":
                message = "order payment authorization failed"
                break
            case "AUTHENTICATION_FAILED":
                message = "order payment authentication failed"
                break
            default:
                message = "order status " + orderStatus
                break
        }

        // removes http field from response, typically you won't send entire structure as response
        return res.send(makeJuspayResponse(statusResponse))
    } catch(error) {
        if (error instanceof APIError) {
            // handle errors comming from juspay's api,
            return res.json(makeError(error.message))
        }
        return res.json(makeError())
    }
})
// block:end:order-status-function


app.get('/', function(req,res) {
    return res.sendfile(path.join(__dirname, 'index.html'))
});

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`)
})

// Utitlity functions
function makeError(message) {
    return {
        message: message || 'Something went wrong'
    }
}

function makeJuspayResponse(successRspFromJuspay) {
    if (successRspFromJuspay == undefined) return successRspFromJuspay
    if (successRspFromJuspay.http != undefined) delete successRspFromJuspay.http
    return successRspFromJuspay
}

```



### Step 1 Add Juspay Order Status function in your backend


Expose `/handleJuspayResponse` API endpoint on your backend that calls the `Order Status` function of PHP SDK. This API endpoint will be called from your frontend to fetch the payment status.

For ease of implementation, you can refer to orderStatus( ) function from ‘Program.php’ file.



#### Code Snippets: -

#### PHP Code Snippet:

```php
public function orderStatus() {
       try {
        $params = array();
        $params ['order_id'] = $this->orderId;
        $requestOption = new RequestOptions();
        $requestOption->withCustomerId("testing-customer-one");
        $order = Order::status($params, $requestOption);
        echo "id: ". $order->orderId . PHP_EOL;
        echo "amount: ". $order->amount . PHP_EOL;
        echo "status: " . $order->status . PHP_EOL;
        echo "order env" . getenv("ORDER_ID") . PHP_EOL;
       } catch ( JuspayException $e ) {
            echo "error code" . $e->getHttpResponseCode() . PHP_EOL;
            echo "error message: " . $e->getErrorMessage() . PHP_EOL;
            echo "error code" . $e->getErrorCode() . PHP_EOL;
        }
    }
```



### Step 1 Add Juspay Order Status function in your backend


Expose `/handleJuspayResponse` API endpoint on your backend that calls the `Order Status` function of Java SDK. This API endpoint will be called from your frontend to fetch the payment status.

For ease of implementation, you can refer to doPost( ) function from ‘HandleJuspayResponse.java’ file.



#### Code Snippets: -

#### Java Code Snippet:

```java
package in.juspaybackendkit;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import in.juspay.exception.*;
import in.juspay.model.Order;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HandleJuspayResponse extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doPost(req, resp);
    }

    // block:start:order-status-function
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String orderId = req.getParameter("order_id");

        if (orderId == null || orderId.isEmpty()) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write(makeErrorMsg("order_id not present or cannot be empty"));
            return;
        }

        try {
            Order orderStatus = Order.status(orderId);

            String message;
            switch (orderStatus.getStatus()) {
                case "CHARGED":
                    message = "order payment done successfully";
                    break;
                case "PENDING":
                case "PENDING_VBV":
                    message = "order payment pending";
                    break;
                case "AUTHORIZATION_FAILED":
                    message = "order payment authorization failed";
                    break;
                case "AUTHENTICATION_FAILED":
                    message = "order payment authentication failed";
                    break;
                default:
                    message = "order status " + orderStatus.getStatus();
                    break;
            }

            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setContentType("application/json");
            JsonObject orderStatusResponse = new JsonObject();
            orderStatusResponse.addProperty("order_id", orderId);
            orderStatusResponse.addProperty("message", message);
            orderStatusResponse.addProperty("order_status", orderStatus.getStatus());
            String jsonString = new Gson().toJson(orderStatusResponse);
            resp.getWriter().write(jsonString);
        }
        catch (JuspayException e) {
            e.printStackTrace();
            resp.setStatus(e.getHttpResponseCode());
            resp.setContentType("application/json");
            resp.getWriter().write(makeErrorMsg(e.getStatus()));
        }
    }
    // block:end:order-status-function

    private String makeErrorMsg(String msg) {
        return "{\n  \"message\": \"" + msg + "\"\n}";
    }
}

```



### Step 1 Add Juspay Order Status function in your backend


Expose `/handleJuspayResponse` API endpoint on your backend that calls the `Order Status` function of .NET SDK. This API endpoint will be called from your frontend to fetch the payment status.

For ease of implementation, you can refer to getOrderStatus( ) function from ‘HandleJuspayResponse.cs’ file.



#### Code Snippets: -

#### .NET Code Snippet:

```.net
public JuspayResponse getOrderStatus (string orderId)
        {
            string customerId = "testing-customer-one";
            RequestOptions requestOptions = new RequestOptions{ CustomerId = customerId };
            return new Order().Get(orderId, null, requestOptions);
        }
```



### Step 2 Fetch Payment Status on Frontend


After completion of a payment session the user will be automatically redirected to your app. You will receive `process_result` callback from the Frontend SDK.

After receiving `process_result` from Frontend SDK, call the API endpoint created in the above step to from your frontend, to fetch the latest order status from bank servers (check [sample response](/hypercheckout-mobile-sdk/flutter/resources/order-status--sample-response)). Please ensure that you verify the order ID and amount transaction.You can refer to ‘response.dart’ file for complete code on payment status handling. In `sendGetRequest()` function call, replace [http://10.0.2.2:5000](http://10.0.2.2:5000) with the URL of your backend.

Create the UI based on the order status response. Please refer to [Transaction Status](/hypercheckout-mobile-sdk/flutter/resources/transaction-status) section to understand how to handle various order status scenarios .

The following figure is a workflow of how you can handle the order status:

![Image](https://dth95m2xtyv8v.cloudfront.net/tesseract/assets/hypercheckout-mobile-sdk/-uMw8o.png)





#### Code Snippets: -

#### PHP Code Snippet:

```php
//10.0.2.2 Works only on emulator
    var response = await http.get(
        Uri.parse(
            'http://10.0.2.2:5000/handleJuspayResponse?order_id=${order_id}'),
        headers: headers);
```

#### Java Code Snippet:

```java
//10.0.2.2 Works only on emulator
    var response = await http.get(
        Uri.parse(
            'http://10.0.2.2:5000/handleJuspayResponse?order_id=${order_id}'),
        headers: headers);
```

#### .NET Code Snippet:

```.net
//10.0.2.2 Works only on emulator
    var response = await http.get(
        Uri.parse(
            'http://10.0.2.2:5000/handleJuspayResponse?order_id=${order_id}'),
        headers: headers);
```

#### NodeJS Code Snippet:

```nodejs
//10.0.2.2 Works only on emulator
    var response = await http.get(
        Uri.parse(
            'http://10.0.2.2:5000/handleJuspayResponse?order_id=${order_id}'),
        headers: headers);
```



### Step 3 Display Payment Status


Once the payment status is determined via the API, the final status should be displayed to the user. This screen needs to be handled by the merchant, it is not provided by the Hypercheckout SDK.

