# Implementing RuPay Authentication Using RuPay JavaScript API
source: https://developer.mastercard.com/mastercard-gateway/documentation/security-and-fraud/authentication/rupay-payer-auth/imp-rupay-auth-rupay-js-api/index.md

This page describes how to integrate to the gateway to use RuPay authentication using the RuPay JavaScript (JS) API.
Warning: The RuPay JS integration guidelines complement the [RuPay Authentication](https://developer.mastercard.com/mastercard-gateway/documentation/security-and-fraud/authentication/rupay-payer-auth/rupay-auth-auth-api/index.md) API integration guidelines and as such must be used with it.

## Step 1: Create and Update Session {#step-1-create-and-update-session}

RuPay JS uses [session-based authentication](https://developer.mastercard.com/mastercard-gateway/documentation/security-and-fraud/secure-int-pw-cert/index.md#session-authentication). As a first step, you must create a session, which you can then update with the request fields and values you wish to store in the session.

You can create a session using the Create Session call. This is a server-side API call and is a prerequisite for integrating with the JS API. It returns the following fields:

* `session.id`: A unique session identifier which you must provide on subsequent requests to reference session contents.
* `session.authenticationLimit`: The limit you supplied in the request or the gateway's default value.
* `session.aes256Key`: The key you can use to decrypt sensitive data passed to your website through the payer's browser or mobile device.
* `session.version`: You can use this field to implement optimistic locking of the session content.
* `session.updateStatus`: A summary of the outcome of the last attempt to modify the session.

**Create Session API Reference** [\[REST\]](https://developer.mastercard.com/mastercard-gateway/documentation/api-reference/v100/rest/api-ops/index.md#session) [\[NVP\]](https://developer.mastercard.com/mastercard-gateway/documentation/api-reference/v100/nvp/api-ops/index.md#session)

### Update Session Request {#update-session-request}

You can add or update fields in a session using the Update Session call. It allows you to add payment and payer data into a session that can subsequently become the input to determine the risk associated with a payer in an authentication operation. The following fields are required in a session:

#### Mandatory Fields {#mandatory-fields}

* `sourceOfFunds.provided.card.*`: Details of the card being used for the payment.
* `order.amount`
* `order.currency`: The currency of the order.
* `transaction.id`: A unique identifier for this payment authentication.
* `order.id`: A unique identifier for this order.
* `authentication.channel=PAYER_BROWSER`: The channel in which the authentication request is being initiated.
* `authentication.purpose=PAYMENT_TRANSACTION`: Indicates the context in which payer authentication is being requested.
* `authentication.redirectResponseUrl`: The URL to which you want to redirect the payer after completing the payer authentication process.

You cannot remove fields from a session but can only overwrite values for existing fields.
**Update Session API Reference** [\[REST\]](https://developer.mastercard.com/mastercard-gateway/documentation/api-reference/v100/rest/api-ops/index.md#session) [\[NVP\]](https://developer.mastercard.com/mastercard-gateway/documentation/api-reference/v100/nvp/api-ops/index.md#session)

## Step 2: Initialize the API {#step-2-initialize-the-api}

Reference the RuPay JS API `rupay.js` from the gateway servers. This places a rupay object into the window/global namespace.
**rupay.js Reference** [\[JavaScript\]](https://developer.mastercard.com/mastercard-gateway/documentation/api-reference/js-libraries/index.md)

Once you have created a session, initialize the API using the configure( ) method. This method should be called during the page load or when the DOM is in ready state. It should be called only once for the page load. After calling this method, RuPay JS will provide configuration values as Member variables.

### RuPay JS Initialization Request {#rupay-js-initialization-request}

You can initialize the RuPay JS API by invoking the configure() method, with the following mandatory fields as arguments in a map object:

* `merchantId`: Your merchant identifier on the gateway.
* `sessionId`: The session ID that you created using the Create Session call.
* `containerId`: The ID in your html where the API injects a hidden iframe.
* `callback`: A function that will be invoked once the API has been initialized.
* `configuration`: JSON value supporting data elements like userLanguage(optional), REST API version (wsVersion).

### Example Initialize API Configuration {#example-initialize-api-configuration}

```html
<html>
    <head>
    <script src="https://{{host}}/static/rupay/1.0.0/rupay.js"
            data-error="errorCallback"
            data-cancel="cancelCallback">
    </script>

    <script type="text/javascript">
        //The output of this call will return 'false', since the API is not configured yet
        console.log(Rupay.isConfigured());
        /**
        Configure method with the configuration{} parameter set and demonstrates the state change of the rupay object before and after the configure method is invoked.
        */
        Rupay.configure({
    merchantId: "TESTMERCHANT",
    sessionId: "SESSION0002899787259G30902270H6",
    containerId: "ABC",
    callback: function() {
        if (Rupay.isConfigured())
            console.log("Done with configure");
    },
    configuration: {
        userLanguage: "en-US",
        wsVersion: 100
    }
});

    </script>
    </head>
    <body>
        <div id="RupayUI"></div>
    </body>
</html>
```

## Step 3: Initiate Authentication {#step-3-initiate-authentication}

Once all payer and payment data has been gathered into a session, you can initiate the authentication by invoking the `initiateAuthentication()` method. It allows you to determine if RuPay payer authentication is available to the merchant for a given card. If the card type is RuPay, the gateway determines the eligibility of the RuPay card BIN for e-commerce transactions.

### Initiate Authentication Request {#initiate-authentication-request}

You can initiate authentication by providing the following mandatory fields in the `initiateAuthentication()` method:

* `orderId`: The unique identifier for this order.
* `transactionId`: The unique identifier for this payment authentication.
* `callback`: The callback function.
* `optionalParams`: (Optional) argument with any additional Initiate Authentication REST API request fields such as correlationId.

### Initiate Authentication Response {#initiate-authentication-response}

If RuPay authentication of the payer is available, the following fields are returned in the data argument of the callback function. Otherwise, the response includes an error.

* `data.restApiResponse`: Contains raw response from the Initiate Authentication REST API call.
* `data.correlationId`: The last correlation ID that was used for making the Initiate Authentication REST API call. It allows you to match the response to the request.
* `data.gatewayRecommendation`

To determine the next step, check the gateway's recommendation provided in the **gatewayRecommendation** field.

|         **gatewayRecommendation**         |                                                                                                                                 **Next step**                                                                                                                                 |
|-------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| PROCEED                                   | You can [proceed to authenticate the payer](https://developer.mastercard.com/mastercard-gateway/documentation/security-and-fraud/authentication/rupay-payer-auth/imp-rupay-auth-rupay-js-api/index.md#step-4-authenticate-payer) using the `authenticatePayer()` method call. |
| RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | Ask the payer for alternative payment details (for example, a new card or another payment method) and resubmit with new details.                                                                                                                                              |

The following table shows the Initiate Authentication response for the various Rupay authentication scenarios.

|                                    **State**                                    |    **response.gatewayRecommendation**     | **transaction.authenticationStatus** |  **response.gatewayCode**  | **result** |
|---------------------------------------------------------------------------------|-------------------------------------------|--------------------------------------|----------------------------|------------|
| Initiate Authentication Complete --- Enrolled (eligible for e-commerce)         | PROCEED                                   | AUTHENTICATION_AVAILABLE             | AUTHENTICATION_IN_PROGRESS | SUCCESS    |
| Initiate Authentication Complete --- Not Enrolled (not eligible for e-commerce) | RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | AUTHENTICATION_NOT_SUPPORTED         | DECLINED                   | FAILURE    |
| Acquirer Timeout                                                                | RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | AUTHENTICATION_UNAVAILABLE           | DECLINED                   | FAILURE    |
| Invalid BIN response from RuPay PaySecure                                       | RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | AUTHENTICATION_NOT_SUPPORTED         | DECLINED                   | FAILURE    |
| If RuPay PaySecure is not able to process transactions                          | RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | AUTHENTICATION_UNAVAILABLE           | DECLINED                   | FAILURE    |

### Example Initiate Authentication Request {#example-initiate-authentication-request}

```js
var optionalParams = {
  sourceOfFunds: {
    type: "CARD"
  },
  order: {
    walletProvider: "MASTERPASS_ONLINE"
  }
};

Rupay.initiateAuthentication({ orderId }, { transactionId }, function (data) {
  if (data && data.error) {
    var error = data.error;

    // Something bad happened, the error value will match what is returned by the Authentication API
    console.error("error.code : ", error.code);
    console.error("error.msg : ", error.msg);
    console.error("error.result : ", error.result);
    console.error("error.status : ", error.status);
  } else {
    console.log("After Initiate RuPay ", data);

    // data.response will contain information like gatewayRecommendation, authentication version, etc.
    console.log("REST API raw response ", data.restApiResponse);
    console.log("Correlation Id", data.correlationId);
    console.log("Gateway Recommendation", data.gatewayRecommendation);
    console.log("HTML Redirect Code", data.htmlRedirectCode);
    console.log("Authentication Version", data.authenticationVersion);

    switch (data.gatewayRecommendation) {
      case "PROCEED":
        authenticatePayer(); // merchant's method
        break;
      case "RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS":
        tryOtherPayment(); // Card does not support 3DS and transaction filtering rules require 3DS on this transaction: Ask the payer to select a different payment method
        break;
    }
  }
}, optionalParams);
```

## Step 4: Authenticate Payer {#step-4-authenticate-payer}

Where the Initiate Authentication response has indicated authentication to be available (**authentication.version=RUPAY** ) for the RuPay card, you can invoke the `authenticatePayer()` method. Invoke this when the payer clicks the "Pay Now" button on the checkout page.

The Authenticate Payer operation securely exchanges necessary information, including the card number, between your acquiring bank and RuPay PaySecure. PaySecure returns a unique Transaction ID `tran_ID`, which may be used in subsequent Authorization or Pay operations.

### Authenticate Payer Request {#authenticate-payer-request}

Invoke the authenticatePayer() method by providing the following mandatory fields:

* `orderId`: The same orderId as the initiateAuthentication() method that preceded it.
* `transactionId`: The same transactionId as the initiateAuthentication() method that preceded it.
* `callback`: The callback function.
* `optionalParams`: (Optional) arguments with any additional Authenticate Payer REST API request fields such as fullScreenRedirect, billing.

### Authentication Payer Response {#authentication-payer-response}

The following fields are returned in the data argument of the callback function:

* `data.restApiResponse`: Contains raw response from the Authentication Payer REST API call.
* `data.correlationId`: The last correlation ID that was used for making the Authentication Payer REST API call. It allows you to match the response to the request.
* `data.gatewayRecommendation`
* `data.htmlRedirectCode`: The gateway always returns this field for insertion into the page displayed to the payer. To determine the next step, check the gateway's recommendation provided in the gatewayRecommendation field returned in the callback.

|         **gatewayRecommendation**         |                                                          **Next step**                                                           |
|-------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| Proceed                                   | You can proceed to complete the authentication process (challenge flow) or proceed to complete the payment (frictionless flow).  |
| DO_NOT_PROCEED_ABANDON_ORDER              | Do not submit the same request again. The payment service provider, scheme, or issuer require you to abandon the order.          |
| RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | Ask the payer for alternative payment details (for example, a new card or another payment method) and resubmit with new details. |

If the gateway recommends you to PROCEED, then paste the content of the htmlRedirectCode response field into the page being displayed to the payer.

The following table shows the authenticatePayer() response for the various Rupay authentication scenarios.

|                         **State**                          |    **response.gatewayRecommendation**     | **transaction.authenticationStatus** | **authentication.payerInteraction** | **response.gatewayCode** | **result** |
|------------------------------------------------------------|-------------------------------------------|--------------------------------------|-------------------------------------|--------------------------|------------|
| Authenticate Payer Successful --- Challenge flow initiated | PROCEED                                   | AUTHENTICATION_PENDING               | REQUIRED                            | PENDING                  | PENDING    |
| Issuer Authentication Failed due to invalid card details   | DO_NOT_PROCEED_ABANDON_ORDER              | AUTHENTICATION_REJECTED              | NOT_REQUIRED                        | DECLINED                 | FAILURE    |
| Acquirer Timeout                                           | RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | AUTHENTICATION_UNAVAILABLE           | NOT_POSSIBLE                        | DECLINED                 | FAILURE    |
| Invalid BIN response from NPCI                             | RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | AUTHENTICATION_UNAVAILABLE           | NOT_POSSIBLE                        | DECLINED                 | FAILURE    |
| If RuPay PaySecure is not able to process transactions     | RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | AUTHENTICATION_UNAVAILABLE           | NOT_POSSIBLE                        | DECLINED                 | FAILURE    |
| System Error (a technical error at RuPay PaySecure)        | RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | AUTHENTICATION_UNAVAILABLE           | NOT_POSSIBLE                        | DECLINED                 | FAILURE    |

#### OTP Authentication {#otp-authentication}

The gateway redirects the payer's browser to the issuer's OTP validation UI where the payer will be prompted to enter a valid OTP, after which the payer will be redirected back to your web site. The following fields are returned in the callback once the payer's browser has been returned to your website.

* `order.id`
* `transaction.id`
* `result`
* `response.gatewayRecommendation` You can determine the authentication outcome using the value returned in the `response.gatewayRecommendation` field.

|    **response.gatewayRecommendation**     |                                                                                                                                                                                                  **Next step**                                                                                                                                                                                                   |
|-------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| PROCEED                                   | You can [proceed with the payment](https://developer.mastercard.com/mastercard-gateway/documentation/security-and-fraud/authentication/rupay-payer-auth/imp-rupay-auth-rupay-js-api/index.md#step-5-use-the-authentication-result-in-a-payment-operation) as authentication is granted. If the Authorization for the payment was successful, proceed with capturing the funds and if applicable, ship the goods. |
| RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | Ask the payer for alternative payment details (for example, a new card or another payment method) and resubmit with new details.                                                                                                                                                                                                                                                                                 |

The gateway updates the Authentication Payer response fields after retrieving the results from the OTP authentication.

|                            **State**                            |    **response.gatewayRecommendation**     | **transaction.authenticationStatus** | **authentication.payerInteraction** | **response.gatewayCode** | **result** |
|-----------------------------------------------------------------|-------------------------------------------|--------------------------------------|-------------------------------------|--------------------------|------------|
| Challenge flow is successful                                    | PROCEED                                   | AUTHENTICATION_SUCCESSFUL            | REQUIRED                            | APPROVED                 | SUCCESS    |
| Challenge flow unsuccessful (for example, timeout, invalid OTP) | RESUBMIT_WITH_ALTERNATIVE_PAYMENT_DETAILS | AUTHENTICATION_FAILED                | REQUIRED                            | DECLINED                 | FAILURE    |

### Example Authenticate Payer Request {#example-authenticate-payer-request}

```js
var optionalParams = {
  fullScreenRedirect: true,
  billing: {
    address: {
      city: "London",
      country: "GBR"
    }
  }
};

Rupay.authenticatePayer("5678", "ABC", function (data) {
  if (!data.error) {
    // data.response will contain all the response payload from the AUTHENTICATE_PAYER call.
    console.log("REST API response ", data.restApiResponse);
    console.log("HTML redirect code ", data.htmlRedirectCode);
  }
}, optionalParams);
```

## Step 5: Use the Authentication Result in a Payment Operation {#step-5-use-the-authentication-result-in-a-payment-operation}

When the result of the authenticatePayer() method indicates that you can proceed with the payment (**gatewayRecommendation=PROCEED**), you may initiate an Authorize or Pay operation. In addition to the Standard fields, you must provide the following fields:

* `order.id`: Provide the orderId that you supplied in the initiateAuthentication() and authenticatePayer() methods.
* `authentication.transactionId`: Provide the transactionId that you supplied in the initiateAuthentication() and authenticatePayer() methods. You do not need to include any of the fields in the authentication parameter group, as the gateway uses the `authentication.transactionId` to look up the authentication results that it stored when you asked it to perform authentication. The gateway passes the required information to the acquirer.

### Example Pay request and response {#example-pay-request-and-response}

| HTTP Method |                                                   URL                                                   |
|-------------|---------------------------------------------------------------------------------------------------------|
| PUT         | https://{{host}}/api/rest/version/100/merchant/{merchantId}/order/{orderid}/transaction/{transactionid} |

```json
{
  "apiOperation": "PAY",
  "order": {
    "amount": "100",
    "currency": "INR"
  },
  "sourceOfFunds": {
    "provided": {
      "card": {
        "expiry": {
          "month": "01",
          "year": "21"
        },
        "number": "6074819900004939",
        "securityCode": "111"
      }
    },
    "type": "CARD"
  },
  "authentication": {
    "transactionId": "8286737"
  }
}
```

```json
{
  "authentication": {
    "transactionId": "471707320"
  },
  "authorizationResponse": {
    "transactionIdentifier": "500000000000000000000002347854"
  },
  "gatewayEntryPoint": "WEB_SERVICES_API",
  "merchant": "TESTMERCHANT",
  "order": {
    "amount": 100.00,
    "chargeback": {
      "amount": 0,
      "currency": "INR"
    },
    "creationTime": "2019-07-03T09:08:28.309Z",
    "currency": "INR",
    "id": "802014086",
    "merchantCategoryCode": "4511",
    "status": "CAPTURED",
    "totalAuthorizedAmount": 100.00,
    "totalCapturedAmount": 100.00,
    "totalRefundedAmount": 0.00
  },
  "response": {
    "acquirerCode": "00",
    "acquirerMessage": "Success",
    "gatewayCode": "APPROVED"
  },
  "result": "SUCCESS",
  "sourceOfFunds": {
    "provided": {
      "card": {
        "brand": "RUPAY",
        "expiry": {
          "month": "1",
          "year": "21"
        },
        "fundingMethod": "DEBIT",
        "issuer": "DMBB9990001",
        "number": "607481xxxxxx4939",
        "scheme": "RUPAY",
        "storedOnFile": "NOT_STORED",
        "tags": "{\"RUPAY_BIN_STATUS_FLAG\":\"ACTIVE\",\"RUPAY_BIN_MESSAGE_TYPE\":\"SMS\"}"
      }
    },
    "type": "CARD"
  },
  "timeOfRecord": "2019-07-03T09:08:28.309Z",
  "transaction": {
    "acquirer": {
      "id": "<acquirer_id>",
      "merchantId": "423555234334123"
    },
    "amount": 100.00,
    "authorizationCode": "143835",
    "currency": "INR",
    "frequency": "SINGLE",
    "id": "108379916",
    "receipt": "918409000035",
    "source": "INTERNET",
    "terminal": "88011019",
    "type": "PAYMENT"
  },
  "version": "100"
}
```

## Test your integration {#test-your-integration}

To test your integration, you can use your TEST merchant profile in the production environment.
**NPCI emulator** [\[REST\]](https://developer.mastercard.com/mastercard-gateway/documentation/test-cards/npci-emulator/index.md)
