# Tutorial: validate your first bank account

import { Tabs, TabItem } from '@astrojs/starlight/components';

In this tutorial you make your first calls to the Risk Intelligence API in the sandbox. You get an access token,
validate two bank accounts with [Account Intelligence](/docs/risk/bank-accounts/account-intelligence), compare a
low-risk result with a high-risk one, and turn each result into a decision your application can act on. Every account
you validate here uses a sandbox test routing number, so each call returns a fixed, known result and nothing reaches a
real financial institution.

By the end you will have:

- Exchanged your client credentials for an access token and a refresh token.
- Validated a business's bank account with Account Intelligence Standard and read its `confidence_score` and
  `decisioning_insights`.
- Seen how a high-risk result differs from a low-risk one.
- Run the same check with Account Intelligence Lite.
- Written a small function that maps each result to approve, review, or decline.
- Refreshed an expired access token and handled a temporary outage.

The tutorial takes about 15 minutes.

## Prerequisites

Before you start, you need:

- A sandbox `client_id` and `client_secret` for the Risk Intelligence API. GrailPay's support team provides them when
  you onboard. If you do not have them, contact [support@grailpay.com](mailto:support@grailpay.com). These are not
  the same credentials as a Payments API key.
- [cURL](https://curl.se/), or any other HTTP client.
- For the decision function in Step 5, one of: a [Laravel](https://laravel.com/) 11 or later application, a
  [Ruby on Rails](https://rubyonrails.org/) 7.0 or later application, Node.js 20 or later, or Python 3.8 or later.

All requests in this tutorial go to the sandbox base URL, `https://risk-api-sandbox.grailpay.com`.

:::caution
The test routing numbers in Steps 2 and 3 return fixed results only in the sandbox. Do not use them to test a
production integration.
:::

## Step 1: Get an access token

The Risk Intelligence API uses JWT-based authentication. You exchange your client credentials for an access token,
then send that token on every request. For the full model, see
[Risk Intelligence API authentication](/docs/risk/authentication).

Send your `client_id` and `client_secret` to `POST /v1/auth`:

```bash title="cURL"
curl --request POST 'https://risk-api-sandbox.grailpay.com/v1/auth' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data '{
    "client_id": "{YOUR_CLIENT_ID}",
    "client_secret": "{YOUR_CLIENT_SECRET}"
}'
```

The response carries two tokens:

```json title="Response"
{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOi...",
    "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOi..."
}
```

- `access_token` authorizes your API requests. It's short-lived.
- `refresh_token` gets you a new access token when the current one expires, without sending your client secret
  again. You use it in Step 6.

Save both tokens in your shell so you can reuse them in the next steps:

```bash title="Shell"
export ACCESS_TOKEN='{ACCESS_TOKEN_FROM_RESPONSE}'
export REFRESH_TOKEN='{REFRESH_TOKEN_FROM_RESPONSE}'
```

**Verify:** The response status is `201`. A `401` with `{"error": "Invalid client credentials"}` means the
`client_id` and `client_secret` do not match. Check that you copied the sandbox pair, not the production pair. A `422`
means a field is missing from the request body.

:::tip
Request a token once and reuse it until it expires. Do not authenticate before every call.
:::

## Step 2: Validate a low-risk account

Account Intelligence validates a bank account from its account and routing numbers. In Standard, the default version,
it returns a `confidence_score` and the `decisioning_insights` behind it. Identity data is optional, but the more you
send, the more meaningful the result.

In this step you validate the bank account of a business, Acme Supply Co., and turn on both identity checks:

- `name_match` compares the name you send with the account holder's name on file.
- `taxpayer_number_match` compares the EIN you send with the account holder's tax ID on file.

Send the request to `POST /api/v3/accounts/validate` with your access token in the `Authorization` header. Routing
number `000000001` is a sandbox test routing number that always returns the low-risk, full-match result. The account
number can be any value of up to 17 digits that is not all zeros.

```bash title="cURL"
curl --request POST 'https://risk-api-sandbox.grailpay.com/api/v3/accounts/validate' \
--header "Authorization: Bearer $ACCESS_TOKEN" \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--include \
--data '{
    "bank_account": {
        "account_number": "123456789",
        "routing_number": "000000001"
    },
    "identity": {
        "organization": {
            "name": "Acme Supply Co",
            "ein": "123456789"
        }
    },
    "actions": {
        "version": "standard",
        "name_match": true,
        "taxpayer_number_match": true
    }
}'
```

The `--include` flag prints the response headers with the body. The response body looks like this:

```json title="Response"
{
    "confidence_score": 0.91,
    "decisioning_insights": {
        "valid_routing_number": true,
        "days_since_first_seen": 365,
        "has_positive_transactions": true,
        "has_negative_transactions": false,
        "has_paid_transactions": true,
        "phone_number_present": true,
        "days_since_last_transaction": 3,
        "name_match": "yes",
        "name_match_score": 0.98,
        "taxpayer_number_match": "yes",
        "account_duplicate": false
    }
}
```

Read it from the top down:

- `confidence_score` is `0.91`. The score runs from `0.00` to `1.00`, and higher is better. A score from `0.90` to
  `1.00` is in the **Very High** band, so GrailPay is highly confident that an ACH payment to or from this account
  processes without an operational return.
- `valid_routing_number` is `true`, so the routing number belongs to an active financial institution.
- `has_positive_transactions` is `true` and `has_negative_transactions` is `false`: the account has a history of
  successful payments and no returns.
- `name_match` is `yes` with a `name_match_score` of `0.98`, and `taxpayer_number_match` is `yes`, so the business
  you named appears to own the account.

Every response also carries an `X-RI-Request-ID` header that identifies the request. Store it with your record of the
check. If a payment to this account is later returned, you send this value as `inference_request_id` when you
[submit feedback](/docs/risk/bank-accounts/account-intelligence#feedback).

**Verify:** The response status is `200` and `confidence_score` is `0.91`. If `name_match` is `not_available`, check
that `actions.name_match` is `true` in your request. Account Intelligence returns the name check only when you
request it.

## Step 3: Validate a high-risk account

Repeat the request with routing number `000000003`. This test routing number always returns the high-risk result, so
you can see what a risky account looks like before one reaches your integration.

```bash title="cURL"
curl --request POST 'https://risk-api-sandbox.grailpay.com/api/v3/accounts/validate' \
--header "Authorization: Bearer $ACCESS_TOKEN" \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data '{
    "bank_account": {
        "account_number": "123456789",
        "routing_number": "000000003"
    },
    "identity": {
        "organization": {
            "name": "Acme Supply Co",
            "ein": "123456789"
        }
    },
    "actions": {
        "version": "standard",
        "name_match": true,
        "taxpayer_number_match": true
    }
}'
```

```json title="Response"
{
    "confidence_score": 0.12,
    "decisioning_insights": {
        "valid_routing_number": true,
        "days_since_first_seen": 10,
        "has_positive_transactions": false,
        "has_negative_transactions": true,
        "has_paid_transactions": false,
        "phone_number_present": false,
        "days_since_last_transaction": 1,
        "name_match": "no",
        "name_match_score": 0.14,
        "taxpayer_number_match": "no",
        "account_duplicate": true
    }
}
```

Compare it with Step 2:

| Field                       | Step 2 (low risk) | Step 3 (high risk) | What changed                                               |
|-----------------------------|-------------------|--------------------|------------------------------------------------------------|
| `confidence_score`          | `0.91`            | `0.12`             | The score falls into the **Risky** band, `0.00` to `0.39`. |
| `has_negative_transactions` | `false`           | `true`             | The account has returned payments in its history.          |
| `days_since_first_seen`     | `365`             | `10`               | GrailPay first saw the account 10 days ago.                |
| `name_match`                | `yes`             | `no`               | The name you sent does not match the account holder.       |
| `taxpayer_number_match`     | `yes`             | `no`               | The EIN you sent does not match the account holder.        |

The routing number is still valid, so a payment would reach the bank. The risk is in who owns the account and how it
has behaved, which is what the insights tell you. For what each insight means, see
[Decisioning Insights](/docs/risk/bank-accounts/account-intelligence#decisioning-insights).

**Verify:** The response status is `200` and `confidence_score` is `0.12`.

:::tip
To see the two middle results, use routing number `000000002` for a medium-risk account with no name or taxpayer
data available, and `000000004` for a close taxpayer match. The full list is in
[Standard Test Routing Numbers](/docs/risk/bank-accounts/account-intelligence#standard-test-routing-numbers).
:::

## Step 4: Try Account Intelligence Lite

Lite answers one question from the account and routing numbers alone: is this account likely valid? It returns a
verdict instead of a score, and it does not use identity data. Use it when you need a fast validity signal and do not
collect identity details.

To request Lite, set `actions.version` to `lite` and send only the bank account. Routing number `000000100` is a Lite
test routing number that returns a `likely` verdict.

```bash title="cURL"
curl --request POST 'https://risk-api-sandbox.grailpay.com/api/v3/accounts/validate' \
--header "Authorization: Bearer $ACCESS_TOKEN" \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data '{
    "bank_account": {
        "account_number": "123456789",
        "routing_number": "000000100"
    },
    "actions": {
        "version": "lite"
    }
}'
```

```json title="Response"
{
    "valid": "likely",
    "supplemental_data": {
        "codes": []
    },
    "live": false
}
```

- `valid` is the verdict: `likely`, `unlikely`, or `indeterminate`.
- `supplemental_data.codes` explains the verdict when there is something to add. It is always present and may be
  empty.
- `live` is always `false` in the sandbox.

Now send routing number `000000107`. The verdict changes to `unlikely`, and `codes` contains code `07`, Potential Risk
Indicator. Match on the `code` value, not on its `description`, because the description is display text and can be
reworded.

**Verify:** The response status is `200` and `valid` is `likely` for `000000100` and `unlikely` for `000000107`. A
`422` means the request turned on `name_match` or `taxpayer_number_match`. Lite supports neither action, so remove
them.

## Step 5: Turn the result into a decision

A score is only useful once your application acts on it. The following function maps an Account Intelligence result to
one of three decisions: approve, review, or decline. It handles both Standard and Lite responses.

The thresholds come from the score bands on the [Account Intelligence](/docs/risk/bank-accounts/account-intelligence#confidence-score)
page. Treat them as a starting point, not a GrailPay recommendation, and set your own to match your risk tolerance
and the cost of a return to your business.

Save the Step 2 and Step 3 response bodies as `low-risk.json` and `high-risk.json`. Then add the function for your
stack and run it on each file. The Laravel example is an Artisan command and the Rails example is a Rake task, so run
both from the root of your application, with the two JSON files saved there. The Node.js and Python examples are
standalone scripts.

<Tabs syncKey="framework">
<TabItem label="Laravel">

```php title="routes/console.php (partial)"
// Map an Account Intelligence response body to approve, review, or decline.
function decide(array $result): string
{
    // A Lite response carries a categorical verdict instead of a score.
    if (isset($result['valid'])) {
        return match ($result['valid']) {
            'likely' => 'approve',
            'unlikely' => 'decline',
            default => 'review',
        };
    }

    $score = $result['confidence_score'];
    $insights = $result['decisioning_insights'];

    // A payment to an invalid routing number generally fails, whatever the score.
    if (! $insights['valid_routing_number']) {
        return 'decline';
    }
    if ($score < 0.40) { // Risky band
        return 'decline';
    }
    if ($score < 0.70) { // OK band
        return 'review';
    }
    // Good or Very High band: approve unless an identity check failed.
    if (($insights['name_match'] ?? null) === 'no' || ($insights['taxpayer_number_match'] ?? null) === 'no') {
        return 'review';
    }

    return 'approve';
}

Artisan::command('grailpay:decide {file}', function (string $file) {
    $this->line(decide(json_decode(file_get_contents($file), true)));
});
```

```bash title="Shell"
php artisan grailpay:decide low-risk.json
php artisan grailpay:decide high-risk.json
```

</TabItem>
<TabItem label="Rails">

```ruby title="lib/tasks/grailpay.rake"
require "json"

# Map an Account Intelligence response body to approve, review, or decline.
def decide(result)
  # A Lite response carries a categorical verdict instead of a score.
  if result.key?("valid")
    return { "likely" => "approve", "unlikely" => "decline" }.fetch(result["valid"], "review")
  end

  score = result["confidence_score"]
  insights = result["decisioning_insights"]

  # A payment to an invalid routing number generally fails, whatever the score.
  return "decline" unless insights["valid_routing_number"]
  return "decline" if score < 0.40 # Risky band
  return "review" if score < 0.70 # OK band
  # Good or Very High band: approve unless an identity check failed.
  return "review" if insights["name_match"] == "no" || insights["taxpayer_number_match"] == "no"

  "approve"
end

namespace :grailpay do
  task :decide, [:file] do |_task, args|
    puts decide(JSON.parse(File.read(args[:file])))
  end
end
```

```bash title="Shell"
bin/rails "grailpay:decide[low-risk.json]"
bin/rails "grailpay:decide[high-risk.json]"
```

</TabItem>
<TabItem label="Node.js">

```javascript title="decide.mjs"
import { readFileSync } from 'node:fs';

// Map an Account Intelligence response body to approve, review, or decline.
function decide(result) {
  // A Lite response carries a categorical verdict instead of a score.
  if ('valid' in result) {
    return { likely: 'approve', unlikely: 'decline' }[result.valid] ?? 'review';
  }

  const score = result.confidence_score;
  const insights = result.decisioning_insights;

  // A payment to an invalid routing number generally fails, whatever the score.
  if (!insights.valid_routing_number) {
    return 'decline';
  }
  if (score < 0.4) { // Risky band
    return 'decline';
  }
  if (score < 0.7) { // OK band
    return 'review';
  }
  // Good or Very High band: approve unless an identity check failed.
  if (insights.name_match === 'no' || insights.taxpayer_number_match === 'no') {
    return 'review';
  }

  return 'approve';
}

// File descriptor 0 is standard input.
console.log(decide(JSON.parse(readFileSync(0, 'utf8'))));
```

```bash title="Shell"
node decide.mjs < low-risk.json
node decide.mjs < high-risk.json
```

</TabItem>
<TabItem label="Python">

```python title="decide.py"
import json
import sys


def decide(result):
    """Map an Account Intelligence response body to approve, review, or decline."""
    # A Lite response carries a categorical verdict instead of a score.
    if "valid" in result:
        return {"likely": "approve", "unlikely": "decline"}.get(result["valid"], "review")

    score = result["confidence_score"]
    insights = result["decisioning_insights"]

    # A payment to an invalid routing number generally fails, whatever the score.
    if not insights["valid_routing_number"]:
        return "decline"
    if score < 0.40:  # Risky band
        return "decline"
    if score < 0.70:  # OK band
        return "review"
    # Good or Very High band: approve unless an identity check failed.
    if insights.get("name_match") == "no" or insights.get("taxpayer_number_match") == "no":
        return "review"
    return "approve"


if __name__ == "__main__":
    print(decide(json.load(sys.stdin)))
```

```bash title="Shell"
python3 decide.py < low-risk.json
python3 decide.py < high-risk.json
```

</TabItem>
</Tabs>

Each run prints one decision per file:

```txt title="Output"
approve
decline
```

**Verify:** The low-risk account is approved and the high-risk account is declined. Run the Step 4 Lite response
through the same function: `likely` returns `approve`.

## Step 6: Refresh the token and handle an outage

Your integration must keep working when the access token expires and when Account Intelligence is temporarily
unavailable. Practice both in the sandbox.

### Refresh an expired access token

When the access token expires, requests return `401` with `{"message": "Unauthorized"}`. Get a new access token by
sending your **refresh token**, not the expired access token, as the bearer token to `POST /v1/auth/refresh`:

```bash title="cURL"
curl --request POST 'https://risk-api-sandbox.grailpay.com/v1/auth/refresh' \
--header "Authorization: Bearer $REFRESH_TOKEN" \
--header 'Accept: application/json'
```

```json title="Response"
{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOi..."
}
```

Replace `ACCESS_TOKEN` with the new value and repeat your last request. The refresh response does not include a new
refresh token. When the refresh token also expires, the refresh request returns `401`, and you authenticate again with
your client credentials as in Step 1.

**Verify:** The response status is `200` and the body contains a new `access_token`. A `401` means you sent the
access token instead of the refresh token, or the refresh token has expired.

### Handle a temporary outage

Routing number `999999999` simulates an upstream outage. Send it in a Standard request:

```bash title="cURL"
curl --request POST 'https://risk-api-sandbox.grailpay.com/api/v3/accounts/validate' \
--header "Authorization: Bearer $ACCESS_TOKEN" \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data '{
    "bank_account": {
        "account_number": "123456789",
        "routing_number": "999999999"
    }
}'
```

```json title="Response"
{
    "error": "Service not available",
    "details": "Upstream account validation provider unavailable."
}
```

A `503` means the account was not evaluated, not that it failed. Retry the request later. Do not treat it as a
decline, and do not pass it to the decision function from Step 5.

**Verify:** The response status is `503`.

## Troubleshooting

| Response                                       | Cause                                                                                                      | Fix                                                                                         |
|------------------------------------------------|------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|
| `401` `{"error": "Invalid client credentials"}` | The `client_id` and `client_secret` do not match.                                                          | Check that you use the sandbox credentials with the sandbox base URL.                       |
| `401` `{"message": "Unauthorized"}`             | The access token is missing, malformed, or expired.                                                        | Check the `Authorization: Bearer` header, or [refresh the token](#refresh-an-expired-access-token). |
| `422` on a Standard request                    | A field failed validation, such as a routing number that is not nine digits, both `individual` and `organization` in `identity`, or `name_match` without an identity. | Read the `errors` object in the response. It names each field that failed.                  |
| `422` on a Lite request                        | The request turns on `name_match` or `taxpayer_number_match`.                                             | Send only the bank account and `actions.version`.                                          |
| `429`                                          | You exceeded the rate limit.                                                                               | Wait for the number of seconds in the `Retry-After` header, then retry.                     |
| `503`                                          | Account Intelligence is temporarily unavailable.                                                           | Retry later. Do not record a decision.                                                     |

## Summary

You authenticated with the Risk Intelligence API, validated a low-risk and a high-risk bank account with Account
Intelligence Standard, ran the same check with Lite, and mapped each result to a decision. You also refreshed an
access token and handled a temporary outage. Your production integration follows the same sequence, with live
results in place of the fixed sandbox ones.

## Next steps

- **Learn every field** — [Account Intelligence](/docs/risk/bank-accounts/account-intelligence) covers the
  versions, every test routing number, all decisioning insights, and the Lite supplemental codes.
- **Report returns** — when a payment to an account you approved is returned, send
  [feedback](/docs/risk/bank-accounts/account-intelligence#feedback) with the `X-RI-Request-ID` you stored in Step 2.
  Feedback improves future results for your accounts.
- **Validate an international account** — use
  [Account Intelligence Global](/docs/risk/bank-accounts/account-intelligence-global).
- **Score the payment itself** — [Transaction Intelligence](/docs/risk/transactions/transaction-intelligence) scores
  a specific transfer between a payer and a payee, and [Guarantees](/docs/risk/transactions/guarantees) returns a
  guarantee decision on a debit.
- **Go live** — switch to the production base URL and your production credentials. See the
  [Risk Intelligence API Overview](/docs/risk/overview#production).