FedNow BaaS API Overview

Prev Next

Overview

The FedNow Banking as a Service (BaaS) API enables the processing of instant payments over the FedNow service for Narmi and fintechs. The API allows fintechs to receive FedNow payments for For Benefit Of (FBO) accounts, as well as sending FedNow payments both for on-core and FBO accounts. To support FBO accounts, the API includes endpoints to manage a mapping of virtual accounts (FBO) and custodial core accounts.

Managing Account Mapping

To support the For Benefit Of (FBO) BaaS account model, the BaaS API relies on keeping a mapping of fintech account number (virtual_account_number) to core account number (custodial_account_number). This also includes the status of virtual_account_numbers (the boolean active). A client integrating with the API should keep this directory up to date by using the accounts endpoint to load the initial list of accounts and their status, as well as updating it with any new accounts that are created and status changes as they happen. The accounts endpoint supports a bulk upload of a CSV file and individual calls per account.

Managing Online Status

The FedNow Service is processing payments 24/7. If a client application is unable to process transactions due to an outage (scheduled or unscheduled), they should sign off via the /fintech/status endpoint (online:false). Once they are back online, they should sign back on (online:true). Payments will be rejected while the client is offline. A fintech that is set to online will only receive payments if the institution is also online. If a fintech is online and the institution is initially not online, the fintech can start receiving payments immediately if the institution changes its status to online.

Flow for Receiving Payments

The following steps are involved with receiving a payment:

1. Incoming payment - Narmi receives an incoming payment via the FedNow Service. The account that the transaction should post to is identified via a routing number and account number.

2. Validation and acceptance - Narmi checks for the account number on both the core and in the virtual account number mapping. If an account is not found or if it is set to inactive, the payment will be rejected. Narmi sends a response to the FedNow Service with a decision on whether to accept or reject the payment.

3. Core posting - After receiving a confirmation of settlement from the FedNow network, Narmi posts the payment to the custodial account on the core.

4. Webhook notification - Narmi sends a webhook event of type post_incoming to the client’s webhook endpoint.

5. Webhook signature verification - Client confirms that Narmi is the originator of the webhook event by verifying its signature.

6. Retrieve posting details - Client makes a GET request to the info_callback_url in the webhook payload, and receives a response with the payment details. When receiving a payment, this response will include the field action: post_incoming, indicating the expected action for the client to take.

7. Ledger posting - Client posts the payment to the account on their ledger.

8. Posting status update - Client makes a POST request to the URL supplied in post_confirm_url with the posting status. If the ledger posting is successful, Narmi updates the payment status to "Posted" and sends a confirmation of posting message to the FedNow system.

Narmi will keep the transaction in a non-terminal status (pending final posting) until receiving a posting_status. If the posting status indicates a posting failure (posting_status: posting_failed), the payment will be transitioned to final_post_failed. Client should not send a posting_status if they are still trying to post the payment.

Flow for Returning a Payment that Was Received

The following steps are involved with returning a payment:

1. Incoming return request - Narmi receives an incoming return request via the FedNow Service. A case is created for a staff member to review.

2. Core posting - If a staff member decides to accept the return, Narmi posts the transaction to the custodial account on the core.

3. Webhook notification (FBO only) - Narmi sends two webhook events to the client’s webhook endpoint:

  • A payment_status event will be sent for the original payment. This can be used to retrieve a posting with the ID for the new payment in related_payments (no action is needed).

  • A post_outgoing event will be sent for the new payment resulting from the return, with the necessary information to retrieve the posting information for the new payment (the return needs to be posted to the ledger).

4. Webhook signature verification - Client confirms that Narmi is the originator of the webhook event by verifying its signature.

5. Retrieve posting details - Client makes a GET request to the info_callback_url in the webhook’s payload, and receives a response with the payment details. For the new payment resulting from the return, this will include the field action: post_outgoing, indicating the expected action for the client.

6. Ledger posting - Client posts the return transaction to the account on their ledger.

7. Posting status update - Client makes a POST request to the URL supplied in post_confirm_url with the posting status. This posting event will be reflected as an event in the payment history.

Flow for Sending Payments

The following steps are involved with sending a payment via the BaaS API:

1. Validate receiving financial institution status - Client confirms that the receiving financial institution is actively accepting FedNow payments by making a GET request to the /status endpoint with the RTN for the institution (/status/?rtn=0123456).

2. Account validation and ledger posting (FBO only) - Client completes any necessary validation for the sending account and posts the withdrawal to the ledger.

3. Call /payment endpoint - Client makes a POST request to the /payment endpoint with the details for the payment.

4. Validation and core posting - Narmi validates the payment details. If any validations fail, the API will respond with a 400 error. If the transaction is successfully posted to the core, the API will respond with the payment identifier.

5. FedNow credit transfer created - Narmi submits the payment to the FedNow network.

6. Status updates - Narmi sends a webhook event with the flow send_payment with any additional payment status updates. An initial update can be expected within 20 seconds. Client should call the supplied info_callback_url for more information about the payment.

Possible statuses are:

  • Payment accepted - The status will be updated to Posted (terminal status).
  • Posting confirmation - If the receiving FI sends a posting confirmation (optional), Narmi will send another webhook event and the payment will have the state_detail:counterparty_posting_confirmed.
  • Payment rejected - The posting will need to be reversed. See details in Variations, below.
  • Other updates - Other payment outcomes do not require action on the client side, but the information is shared via webhooks and the /posting endpoint.

Variations of the Flow for Sending Payments

Rejected Payment

If, after steps 1-5 above, the payment is rejected:

1. Status update - Narmi sends a webhook event with the flow send_payment. Client should call the supplied info_callback_url for more information about the payment.

  • For FBO accounts - A rejected payment will show up as: status: rejected_pending_reversal, action:‘reverse_posting. Client should reverse the payment on the ledger and call the URL supplied in post_confirm_url once complete.
  • For on-core accounts - A rejected payment will show up as: Status: rejected_reversed. Client can notify users, as appropriate, but no action is needed.

Accepted Without Posting

If, after steps 1-5 above, the payment results in "Accepted without posting":

1. Status update - Narmi sends a webhook event with the flow send_payment. Client should call the supplied info_callback_url for more information about the payment.

  • accepted_without_post - This status means that the receiving FI needs to manually review the payment before posting it to the recipient account.
  • Final update - A final update should be provided by midnight Eastern time of the following business day. The possible outcomes are:
    • Posted - Payment was posted by counterparty. State_detail: counterparty_posting_confirmed.
    • Rejected - This will result in a separate return payment. See "Requesting a Return Payment" below.
    • Blocked

Requesting a Return Payment

The sending financial institution can send a request for a payment to be returned. If the recipient financial institution accepts the request, the return will be processed as a new payment. An incoming new payment that is a return will include the field related_payment with the payment ID for the original payment.

Webhook Events

API clients will be notified of new events via webhooks. Webhook events are signed with a shared secret, and the signature must be verified to ensure they originated from Narmi. Client must supply Narmi with a URL to receive webhook events.

The webhook events have the following fields:

  • event_kind - identifying the event that has taken place

    • post_incoming
    • post_outgoing
    • payment_status
  • info_callback_url - The URL for the client to call in order to retrieve additional information. Requests should be made to this URL exactly as indicated, including any query parameters.

We recommend setting up the webhook endpoint as IP-restricted. The following are the egress IPs for Narmi webhook events:

  • 3.82.234.74/32
  • 34.237.94.20/32
  • 3.208.59.122/32
  • 44.222.14.27/32
  • 52.72.32.244/32
  • 18.209.25.43/32
  • 54.159.46.110/32

import hmac
import hashlib
import base64


NARMI_WEBHOOK_UUID = ''
NARMI_WEBHOOK_SECRET = ''


def validate_webhook_request(event):
   expected_signature = calculate_expected_signature(event)
   expected_signature_string = construct_expected_signature_string(expected_signature)
   actual_signature_string = event['headers']['x-signature-digest']


   print(f"E: {expected_signature_string}")
   print(f"A: {actual_signature_string}")


   return expected_signature_string == actual_signature_string


def calculate_expected_signature(event):
   date = event['headers']['date']
   method = event['requestContext']['http']['method']
   path = event['requestContext']['http']['path']
   host = event['headers'].get('host')
   content_type = event['headers']['content-type']
   content_length = event['headers']['content-length']


   expected_signature_input = f"date: {date}\n(request-target): {method.lower()} {path}\ncontent-type: {content_type}\ncontent-length: {content_length}\nhost: {host}"


   secret = NARMI_WEBHOOK_SECRET.encode('utf-8')
   signature = hmac.new(secret, expected_signature_input.encode('utf-8'), hashlib.sha256).digest()
   return base64.b64encode(signature).decode('utf-8')




def construct_expected_signature_string(expected_signature):
   key_id_string = f'keyId="{NARMI_WEBHOOK_UUID}"'
   algorithm_string = 'algorithm="hmac-sha256"'
   signature_string = f'signature="{expected_signature}"'
   headers_string = 'headers="date (request-target) content-type content-length host"'
   return f"{key_id_string},{algorithm_string},{signature_string},{headers_string}"




# Example usage with a mock event
mock_event = {
   'headers': {
       'date': '2024-05-21T15:20:52.767886+00:00',
       'content-type': 'application/json',
       'content-length': '146',
       'x-signature-digest': 'keyId=\"[key_id]\",algorithm=\"hmac-sha256\",signature=\"Hu2+C9ouA/MRQrmOIuPQfZnvOM5FmacL42AS9yeD8bA=\",headers=\"date (request-target) content-type content-length host\"',
       'host': '[webhook endpoint hostname]'
   },
   'requestContext': {
       'http': {
           'method': 'POST',
           'path': '/'
       }
   }
}


try:
   if validate_webhook_request(mock_event):
       print("Webhook request is valid.")
   else:
       print("Webhook request is invalid.")
except ValueError as e:
   print(e)

Integration Details

Authentication

The BaaS FedNow API relies on bearer token authentication. The bearer token must be kept secret (treat it like a password) and never exposed to a front-end. If you believe the bearer token has been exposed, you must contact security@narmi.com immediately.

IP Addresses

Before integrating with the API, provide Narmi with the egress IP(s) so they can be granted access to the API.

User Agent

To ensure that requests pass through the Web Application Firewall (WAF), include a user-agent header to identify the application when obtaining an access token or making requests to the Public API. We recommend the following format: User-Agent: integrator_name-fintech_name.

Header Signing

Requests to Narmi BaaS APIs must be signed. This requires the client to have been issued a secret, which it uses to construct headers. The secret must never leave the server and should be treated as a password. If you believe the secret has been exposed, you must contact security@narmi.com. The API uses these headers to verify the authenticity of the request. These headers are required in addition to bearer authentication. This is done following the draft specification on HTTP request signing.

The BaaS FedNow API requires header signature using the following fields:

  • Date
  • request-target
  • Content-type
  • Content-length
  • host
import json
import httpsig
import requests
from datetime import datetime, UTC
from urllib.parse import urlparse


ALGORITHM = "hmac-sha256"
SIGNED_HEADERS = [
   "date",
   "(request-target)",
   "content-type",
   "content-length",
   "host",
]


def generate_request_signature(
   key_id: str, secret: str, method: str, url: str, payload: dict | None = None
) -> tuple[str, str]:
   if payload:
       content = json.dumps(payload)
       content_length = len(content.encode())  # byte size
   else:
       content_length = 0
   date = datetime.now(tz=UTC).isoformat()
   url_parts = urlparse(url)
   hs = httpsig.HeaderSigner(
       key_id, secret, algorithm=ALGORITHM, headers=SIGNED_HEADERS
   )
   hs.signature_template = (
       'keyId="{}",algorithm="{}",signature="%s",headers="{}"'.format(
           key_id, ALGORITHM, " ".join(SIGNED_HEADERS)
       )
   )
   signature = hs.sign(
       {
           "Date": date,
           "Content-Type": "application/json",
           "Content-Length": content_length,
           "Host": url_parts.hostname,
       },
       method=method,
       path=url_parts.path or "/",
   )
   return signature["authorization"], date


key_id = "key_id"
secret = "secret"
token = "token"
method = "GET"
url = "https://[hostname]/baas/fintech/status/"
signature, date = generate_request_signature(key_id, secret, method, url, None)
headers = {
 "X-Signature-Digest": signature,
 "Date": date,
 "Content-Type": "application/json",
 "Authorization": f"Token {token}",
}
r = requests.get(url, headers=headers)
r.status_code
# 200
r.json()
# {'online': True}

const crypto = require("crypto");

/**
 * 
 * @param {string} token Token of the narmi API access token
 * @param {string} secret Secret of the narmi API access token
 * @param {string} method HTTP method used
 * @param {string} url URL of the endpoint
 * @param {object | null} payload Optional object to be JSON encoded as the request payload
 * @returns {object} Signed required headers for narmi API authorization
 */
function generateSignedRequestHeaders(token, keyId, secret, method, url, payload=null) {
  const date = new Date(Date.now()).toISOString();
  const length = payload !== null ? Buffer.byteLength(JSON.stringify(payload)) : 0;
  const urlParts = new URL(url)
  const signList = []
  signList.push(`date: ${date}`)
  signList.push(`(request-target): ${method.toLowerCase()} ${urlParts.pathname}`)
  signList.push(`content-type: application/json`)
  signList.push(`content-length: ${String(length)}`)
  signList.push(`host: ${urlParts.hostname}`)
  
  const signature = crypto
    .createHmac("sha256", secret)
    .update(signList.join('\n'), "ascii")
    .digest("base64");
  const sigHeader = `keyId="${keyId}",algorithm="hmac-sha256",signature="${signature}",headers="date (request-target) content-type content-length host"`;
  const requestHeaders = {
    Authorization: `Token ${token}`,
    Date: date,
    "Content-Type": "application/json",
    "X-Signature-Digest": sigHeader,
  };
  return requestHeaders;
}
// fill in
const token = ""
const keyId = ""
const secret = ""

async function run(){
    const url = "https://[hostname]/baas/fintech/status/";

    const headers = generateSignedRequestHeaders(token, keyId, secret, "GET", url)
    const resp = await fetch(url, {
        headers: headers,
    })
    console.log(resp.status)
    console.log(await resp.json())
}
run()

CSV Upload Sample Python Code

import json
import httpsig
import requests
from datetime import datetime, UTC
from urllib.parse import urlparse
from requests_toolbelt import MultipartEncoder


ALGORITHM = "hmac-sha256"
SIGNED_HEADERS = [
   "date",
   "(request-target)",
   "content-type",
   "content-length",
   "host",
]


key_id = "key_id"
secret = "secret"
token = "token"


def generate_request_signature(
       key_id: str, secret: str, method: str, url: str, encoder
) -> tuple[str, str]:
   content_length = encoder.len
   date = datetime.now(tz=UTC).isoformat()
   url_parts = urlparse(url)
   hs = httpsig.HeaderSigner(
       key_id, secret, algorithm=ALGORITHM, headers=SIGNED_HEADERS
   )
   hs.signature_template = (
       'keyId="{}",algorithm="{}",signature="%s",headers="{}"'.format(
           key_id, ALGORITHM, " ".join(SIGNED_HEADERS)
       )
   )
   signature = hs.sign(
       {
           "Date": date,
           "Content-Type": encoder.content_type,
           "Content-Length": content_length,
           "Host": url_parts.hostname,
       },
       method=method,
       path=url_parts.path or "/",
   )


   return signature["authorization"], date






def upload_accounts():
   method = "POST"
   url = "https://[hostname]/baas/accounts/upload/"
   path = 'accounts.csv'
   with open(path, 'rb') as f:
       encoder = MultipartEncoder(
           fields={
               'file': (path, f, 'text/csv')
           }
       )


       signature, date = generate_request_signature(key_id, secret, method, url, encoder)
       headers = {
           "X-Signature-Digest": signature,
           "Date": date,
           "Content-Type": encoder.content_type,
           "Authorization": f"Token {token}",
       }


       r = requests.post(url, headers=headers, data=encoder)
       print(r.status_code)
	if r.status_code not in [404,500]:
           print(json.dumps(r.json()))


print("calling upload_account: ")
upload_accounts()