Fetch balance

Fetch your customer’s bank balance in real-time

Overview

Balance is an Okra product for receiving real-time balance information data programmatically via /balance/check API.

How to add balance to your app

In this guide, we'll walk through from scratch, how to use the Balance API in your project
If you're familiar with using Okra and already have Okra setup on your machine, you can skip to Identity API, otherwise, carefully follow the next section.

Okra API keys

If you're new to Okra, you'll need to create an Okra developer account.
After creating your account, you'll need to login.
To find your API keys, navigate to the Settings menu on the Okra developer dashboard.
To better understand how Okra API keys work, check this tutorial

Balance model

Before diving deep into the tutorial, you might need to get yourself familiar with the balance object models.

Field

Description

id
ObjectID

Unique Auth ID (Unique Okra Identifier)

available_balance
Number

Amount of Available Funds in the Account

ledger_balance
Number

The Closing Balance of the Account

account
ObjectID

Unique Account ID (Unique Okra Identifier)

connected
Boolean

Customer Connection Status (Did they Choose to Connect this Account to You?)

customer
ObjectID

Unique Customer ID (Unique Okra Identifier)

See Manage Customers ]

record
ObjectID

Unique Record ID (Unique Okra Identifier)

See Records

owner
ObjectID

Unique Company ID (Unique Okra Identifier) (Your Client Token)

env
String

Okra API Env the Auth was Pulled from production or production-sandbox

created_at
Date

Date of Authentication

last_updated
Object

Last Date of Authentication

Install Okra Libraries

Depending on your integration you can install any of our libraries/SDK, to fetch real-time balance.
Check the list of libraries you can use.

Using the Okra Widget

You can check for an account balance using the Okra widget.

  • Step1. - Install the okra-js package by running npm install okra-js
  • Step2. - Use the buildWithOptions approach.
    - Pass in auth, balance into the products array
    During account lnking you'll seee the account balance of customers, and also be sent the success event to your webhook if provided.
import Okra from 'okra-js'

Okra.buildWithOptions({
    name: 'Your company',
    env: 'production-sandbox',
    app_id: ''// app_id from your app builder
    key: '', // Your key from the Okra dashboard
    webhook_url: ''// Your webhook url
    token: '', // Your token from the okra dashboard
    products: ['auth', 'balance'], //in lowercase
    showBalance: true;
    onSuccess: function(data){
        console.log('options success', data)
    },
    onClose: function(){
        console.log('options close')
    }
})

How to check the balance via the API

You can easily understand if a user's balance has changed before making calls to get a real-time balance.

  1. Make a POST request to https://api.okra.ng/v2/balance/check with the account_id
curl -X POST https://api.okra.ng/v2/balance/check
-H 'Content-Type: application/json' 
-H 'Authorization: Bearer <secretKey>'
-d '{ 
            account_id: "xxxxxxxxxxxx" 
        }'
  1. After two minutes, make a GET request to data.callback_url in the response in step 1
curl -X GET https://api.okra.ng/v2/callback?record={recordId}&method=CHECK_BALANCE
-H 'Content-Type: application/json' 
-H 'Authorization: Bearer <secretKey>'
{
    "status": "success",
    "message": "Successfully checked balance",
    "data": {
        "balance_changed": false,
        "last_checked": "2021-07-16T14:20:05.968Z",
        "last_fetched": "2021-07-15T01:02:01.615Z"
    }
}

📘

NOTE

Add a debounce of about 60 seconds to accommodate for banks with duplicate delays

Balance callback

When you refresh balance, the response is not instantaneous because we must interact with the customer's financial institution. As a result, you will receive a callback_url as in the JSON response example below. You can view an example on how to handle the response and retrieve the balance in real time.
Checkout our API Reference to see how it works.

exports.fetchBalance = async (req, res, next) => {
    req.setTimeout(0)
    const baseURL = 'https://api.okra.ng/v2' 
    const { account_id, waitTime } = req.body //waitTime is in minutes
    const token = `Your_JWT_token`
    let config = {
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`
        }
    }
    const getBalanceReq = () => {
        try {
            return axios.post(`${baseURL}/balance/refresh`, { account_id: account_id },config)
        } catch (error) {
            console.error(error)
        }
    }
    const getCallBackData = (data) => {
        try {
            return axios.get(data, config)
        } catch (error) {
            console.error(error)
        }
    }
    const getCallBackReq = async () => {
        getBalanceReq()
            .then(async response  => {
                if (response.data.data) {
                    await waitFor(waitTime * 60000) // covert minutes to milliseconds
                    return [ response.data.data.callback_url.replace("undefined", "callback")].join('')
                }
            }).then(callBack => {
                getCallBackData(callBack)
                    .then(response => {
                       res.json(response.data)
                    })
                    .catch(error => {
                        console.log(error)
                    })
            })
            .catch(error => {
                console.log(error)
            })
    }
    getCallBackReq()
}

const waitFor = (ms) => new Promise(r => setTimeout(r, ms))
{
    "status": "success",
    "message": "Successfully checked balance",
    "data": {
        "balance_changed": true,
        "last_checked": "Fri Jan 01 2021 21:25:05 GMT-0500"
    }
}

Current and periodic balance

Balance typically returns both ledger and available balance information. For fraud detection and insufficient funds (NSF) prevention use cases, the available balance should be used, as it represents the predicted balance net of any pending transactions, while the ledger balance does not take pending transactions into account.

Available balance indicates the balance that is available to spend, which is not the same as the overall value of the account. In some cases, a financial institution may not return available balance information.

If that happens, you can calculate the available balance by starting with the current balance, then using our Transaction product to detect any pending transactions and adjust the balance accordingly. You can also view the balance at each transaction by using our Enhanced Balance product.

🚀Now that you understand how the balance works, check out the API Reference) page to test the balance API in real-time.


Did this page help you?